c++ - Boost MultiIndex 中的复合键语法

标签 c++ boost

即使在研究了 examples 之后,我无法弄清楚如何使用 MultiIndex 容器上的复合键提取范围。

typedef multi_index_container<
  boost::shared_ptr< Host >,
  indexed_by< 
    hashed_unique< const_mem_fun<Host,int,&Host::getID> >, // ID index
    ordered_non_unique< const_mem_fun<Host,int,&Host::getAgeInY> >, // Age index
    ordered_non_unique< const_mem_fun<Host,int,&Host::getHousehold> >, // Household index
    ordered_non_unique< // Age & eligibility status index
      composite_key<
         Host,
        const_mem_fun<Host,int,&Host::getAgeInY>,
        const_mem_fun<Host,bool,&Host::isPaired>
        >
       >
    > // end indexed_by
  > HostContainer;

我的目标是获得一个迭代器,该迭代器指向 HostContainer hmap 中具有年龄 partnerAge 的第一个元素子集并返回 falseHost::isPaired():

  std::pair< hmap::iterator,hmap::iterator > pit = hmap.equal_range(boost::make_tuple( partnerAge, false ) );

我认为这是非常错误的。

  1. 如何/在何处指定迭代器索引(年龄和资格应为 3)?将来我会包括其他复合键。
  2. std::pair 中的两个迭代器究竟是什么? (我正在从一个我不理解的示例中复制语法。)
  3. 理想情况下,我会使用 std::count 来计算符合条件的年龄 partnerAge 元素的数量(返回 falseHost::isPaired())。提取满足这些要求的排序索引的语法是什么?

我显然还在学习 C++ 语法。在此先感谢您的帮助。

最佳答案

要访问第 N 个索引,您可以使用函数 get如下:

std::pair< hmap::nth_index<3>::type::const_iterator,
           hmap::nth_index<3>::type::const_iterator > pit = 
  hmap.get<3>().equal_range(boost::make_tuple( partnerAge, false ) );

equal_range返回第 N 个索引的迭代器对。您将获得满足指定条件的元素范围,因为您的组合键不是唯一的。要遍历该范围,您可以使用从第一个迭代器到第二个迭代器的循环。

考虑使用命名索引将它们用作 get<index_name>() , 因为指定实际数字不是很可读。

count语法类似于 equal_range :

size_t cnt = hmap.get<3>().count(boost::make_tuple( partnerAge, false ) );

关于c++ - Boost MultiIndex 中的复合键语法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2669770/

相关文章:

c++ - 如何使用regex_search获取报价内的内容

c++ - 访问 QMap 的 QMap<QString, QPair<int, int>>

c++ vector 列表初始值设定项不适用于我的类的类型转换构造函数

c++ - 安装旧的 2005 BOOST 库时遇到问题

c++ - 任何人都可以解释 boost::thread 的这个意外结果吗?

c++ - 什么使某些东西成为 C++ 中的抽象类

c++ - 如何使用C++中带有不可复制成员的initializer_list创建映射?

c++ - trunc 函数是否很慢?

python - 在 boost python 中 pickle 一个 vector ?

c++ - 一种将 boost::posix_time::ptime 转换为 __int64 的方法