在 boost 元组向量中查找元素的位置

Find position of element in a vector of boost tuples

我正在遍历 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!

为什么?我的代码中的错误在哪里?

正如 Quentin 在评论中所写,boost::tuple 中的 std::vector 可以用 std::find_if 搜索,就像任何其他类型一样。

However I would also like to find the exact position of this element in the vector in order to delete it later.

请注意 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);
 }