Найти положение элемента в векторе буст-кортежей

Я перебираю вектор boost :: tuples, чтобы найти элемент. Однако я также хотел бы найти точное положение этого элемента в векторе, чтобы потом его удалить.
Это код, однако std :: distance не дает мне правильного значения.

int Controller::isValid(int Id, int& pos) {

pos = 0;

for( std::vector< boost::tuple<int,std::string, std::string, std::string> >::const_iterator it = games.begin(); it != games.end(); it++) {

if( boost::get<0>(*it) == Id) {
pos = std::distance< std::vector< boost::tuple<int,std::string, std::string, std::string> >::const_iterator >( games.begin(), it ) ;
return 0;
}
}

Например, для вектора с размером, равным 5, std :: distance равно 8!

Зачем? Где ошибка в моем коде?

0

Решение

Как писал Квентин в комментариях, std::vector из boost::tupleможно искать с помощью std::find_if, как и любой другой тип.

Однако я также хотел бы найти точное положение этого элемента в векторе, чтобы потом его удалить.

Обратите внимание, что std::vector::erase позволяет стереть элемент его итератором.

 #include <algorithm>
#include <iostream>
#include <vector>
#include <string>

#include <boost/tuple/tuple.hpp>

int main() {
using tup_t =  boost::tuple<int,std::string, std::string, std::string>;
std::vector<tup_t> games{
boost::make_tuple(2, "hello", "world", "bye"),
boost::make_tuple(1, "foo", "bar", "baz")};
auto found = std::find_if(
std::begin(games), std::end(games), [](const tup_t &t){ return boost::get<0>(t) == 1; });
std::cout << std::distance(std::begin(games), found) << std::endl;

if(found != std::end(games))
games.erase(found);
}
1

Другие решения

Других решений пока нет …

По вопросам рекламы ammmcru@yandex.ru
Adblock
detector