【发布时间】:2020-03-03 20:42:58
【问题描述】:
这是一个带有散列索引和序列索引的整数容器:
#include <iostream>
#include <boost/multi_index_container.hpp>
#include <boost/multi_index/hashed_index.hpp>
#include <boost/multi_index/identity.hpp>
#include <boost/multi_index/sequenced_index.hpp>
int main()
{
boost::multi_index_container<
int,
boost::multi_index::indexed_by<
boost::multi_index::hashed_unique<boost::multi_index::identity<int>>,
boost::multi_index::sequenced<>
>
> c;
for (int i=99; i>=0; --i) c.get<0>().insert(i);
for (int j : c.get<0>()) std::cout << " " << j;
std::cout << std::endl;
for (int k : c.get<1>()) std::cout << " " << k;
std::cout << std::endl;
return 0;
}
当我运行它时,我得到:
3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 99 98 97 96 95 94 93 92 91 90 89 88 87 86 85 84 83 82 81 80 79 78 77 76 75 74 73 72 71 70 69 68 67 66 65 64 63 62 61 60 59 58 57 56 55 54 53 52 51 50 49 48 47 2 1 0
99 98 97 96 95 94 93 92 91 90 89 88 87 86 85 84 83 82 81 80 79 78 77 76 75 74 73 72 71 70 69 68 67 66 65 64 63 62 61 60 59 58 57 56 55 54 53 52 51 50 49 48 47 46 45 44 43 42 41 40 39 38 37 36 35 34 33 32 31 30 29 28 27 26 25 24 23 22 21 20 19 18 17 16 15 14 13 12 11 10 9 8 7 6 5 4 3 2 1 0
第一行显示元素通过哈希索引“分散”,正如预期的那样。第二行显示元素通过序列索引按插入顺序排列。但是元素是通过哈希索引插入的;我们对有序索引的元素有什么期望?也就是说,当insert为一个索引调用时,是否定义了用于“其他”索引的插入函数?
具体来说:当一个多索引容器有一个散列索引和一个序列索引,并且元素只通过散列索引插入时,元素是否总是通过有序索引按插入顺序排列?
【问题讨论】:
-
这就是"sequenced" index_by key的定义。在内部,boost 会按照自然顺序维护从键空间到列表的多个映射。如果您想到一个复杂数据集的 multi_index_containers 以及集合中不同字段的 index_by 键,则更容易可视化。以这种方式设想时,每个字段都有自己的排序映射,允许基于该键进行快速查找。当使用顺序键而不是使用其中一个字段时,您只需使用它的插入顺序。保证按key的顺序进行迭代
标签: c++ boost boost-multi-index