c++ - 在 boost::multi_index 中访问 hashed_unique 中的数据

标签 c++ boost boost-multi-index

我第一次尝试使用 boost 的多索引,我似乎无法理解我在网络上看到的所有代码。

首先:我的目标是拥有一个带有枚举的容器作为直接访问的键,并且能够根据原始插入顺序对其进行迭代。

我已经像这样定义了我的 boost 元素:

struct VarMapEle {
    SolutionVariableNames first;
    uint    second;
};

struct var_tag {};
struct rand_tag {};

typedef multi_index_container<
    VarMapEle,
    indexed_by< 
        random_access<tag<rand_tag>>, // this index represents insertion order
        hashed_unique<tag<var_tag>, member<VarMapEle, SolutionVariableNames,     &VarMapEle::first>>
        >
> VariableMap;

我怎样才能完成我之前提到的任一项任务?

最佳答案

A multi_index_container可以被认为是一堆容器(在你的例子中,一个 std::vector -like -- random_acces -- 另一个类似于 std::unordered_set -- hashed_unique --)恰好作用于相同的底层元素集合。使用 get<tag>() 访问每个“容器”或索引get<n>()其中 n 是在 indexed_by 中指定的从 0 开始的索引顺序部分。因此,要按照插入顺序遍历元素,您需要访问索引 #0 并像使用 std::vector 一样使用它。 :

for(const VarMapEle& e:m.get<rand_tag>()){
    std::cout<<e.first<<","<<e.second<<"\n";
}

类似地,查找工具由索引 #1 提供:

auto it=m.get<var_tag>().find(SolutionVariableNames{1});
std::cout<<it->second<<"\n";

关于c++ - 在 boost::multi_index 中访问 hashed_unique 中的数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34338048/

相关文章:

c++ - 在结构内部定义时初始化 Boost.MultiArray?

c++ - boost.multiindex 和值的地址作为键

boost - 从 Boost MultiIndex 中删除

c++ - 二维 vector 未正确保存和加载 boost::serialize 库

c++ - 输出指针的 const 前缀

c++ - boost 几何 : intersection of a polygon and a box

c++ - 使用 boost.signals2 如何将动态分配的对象连接到信号

c++ - 容器模板参数 std::map 或 std::vector

c++ - vector 对而不是 vector <pair>?

c++ - 捕获 EXCEPTION_GUARD_PAGE 是否安全