Reputation: 6758
I am iterating over a vector of boost::tuples in order to find an element. However I would also like to find the exact position of this element in the vector in order to delete it later. This is the code, however the std::distance does not give me correct value.
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;
}
}
For example for a vector with size equals to 5, the std::distance is 8!
Why? Where is the bug in my code?
Upvotes: 0
Views: 526
Reputation: 76297
As Quentin wrote in the comments, an std::vector
of boost::tuple
s can be searched for with std::find_if
, just like any other type.
However I would also like to find the exact position of this element in the vector in order to delete it later.
Note that std::vector::erase
allows you to erase an element by its iterator.
#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);
}
Upvotes: 1