0

我正在迭代 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!

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

4

1 回答 1

1

正如 Quentin 在评论中所写,可以使用 搜索an std::vectorof s ,就像任何其他类型一样。boost::tuplestd::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);
 }
于 2016-09-27T12:09:11.243 回答