【发布时间】:2015-03-30 06:12:36
【问题描述】:
我正在使用 boost::multi_index::multi_index_container 的 boost 库。
我想存储与此容器中存在的每个元素相关的值。
我们可以修改这个容器以使用多映射以及它将用作多索引容器吗?
【问题讨论】:
标签: c++ boost multimap boost-multi-index
我正在使用 boost::multi_index::multi_index_container 的 boost 库。
我想存储与此容器中存在的每个元素相关的值。
我们可以修改这个容器以使用多映射以及它将用作多索引容器吗?
【问题讨论】:
标签: c++ boost multimap boost-multi-index
当然。
但是,首先看看 Boost Bimap,因为它似乎已经完成了您所描述的操作:
我在这里给出了一个如何使用 Boost Multi Index 来模拟地图的示例:
相关的类型机器如下所示:
namespace emulation {
template <typename T1,typename T2,typename Alloc>
struct mutable_pair
{
typedef T1 first_type;
typedef T2 second_type;
mutable_pair(Alloc alloc):first(T1(alloc)),second(T2(alloc)){}
mutable_pair(const T1& f,const T2& s):first(f),second(s){}
mutable_pair(const std::pair<T1,T2>& p):first(p.first),second(p.second){}
T1 first;
mutable T2 second;
};
using namespace boost::multi_index;
template <typename Key, typename T, typename Compare, typename Allocator, typename Element = mutable_pair<Key, T, Allocator> >
using map = multi_index_container<
Element,
indexed_by<
ordered_unique<member<Element,Key,&Element::first>,Compare>
>,
typename Allocator::template rebind<Element>::other
>;
template <typename Key, typename T, typename Compare, typename Allocator, typename Element = mutable_pair<Key, T, Allocator> >
using multimap = multi_index_container<
Element,
indexed_by<
ordered_non_unique<member<Element,Key,&Element::first>,Compare>
>,
typename Allocator::template rebind<Element>::other
>;
}
如果您希望答案包含完整的演示,尽管它包含一些不相关的复杂性以便使用共享内存分配器。
【讨论】: