c++ - 在 boost 元组 vector 中查找元素的位置

标签 c++ boost boost-tuples

我正在迭代一个 boost::tuples vector 以找到一个元素。但是我也想找到这个元素在 vector 中的确切位置,以便以后删除它。 这是代码,但是 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 的 vector ,std::distance 为 8!

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

最佳答案

正如 Quentin 在评论中所写,boost::tuplestd::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);
 }

关于c++ - 在 boost 元组 vector 中查找元素的位置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39723329/

相关文章:

c++ - Boost::tuple 相当于 Python 的 itemgetter?

c++ - 如何为 3 个数据集创建多 MAP

c++ - 带有 unique_ptr 参数的 std::function

c++ - 错误:boost.fusion::for_each() 和从 boost.tuple 派生的结构

c++ - 模板函数错误(使用 Boost.Tuples)

c++ - 如何使用 C++ boost::asio 顺序执行异步操作?

在 C++ 中具有多个枚举参数的 C++ 函数模板部分特化?

C++ UUID 到 STL 字符串

c++ - boost相当于windows mutex

c++ - 将子树添加到 boost::property_tree 元素