【问题标题】:Can we use boost::multi_index::multi_index_container as a multiindex map?我们可以使用 boost::multi_index::multi_index_container 作为多索引映射吗?
【发布时间】:2015-03-30 06:12:36
【问题描述】:

我正在使用 boost::multi_index::multi_index_container 的 boost 库。

我想存储与此容器中存在的每个元素相关的值。

我们可以修改这个容器以使用多映射以及它将用作多索引容器吗?

【问题讨论】:

    标签: c++ boost multimap boost-multi-index


    【解决方案1】:

    当然。

    但是,首先看看 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
        >;
    }
    

    如果您希望答案包含完整的演示,尽管它包含一些不相关的复杂性以便使用共享内存分配器。

    【讨论】:

    • 感谢您提供描述性和有用的答案。但是我被困在地图关联容器的模拟中。我试图模拟一个将键和值保存为 boost:shared_ptr. 的“set”的映射
    • @BSalunke 也许你应该发布另一个问题,显示你被困在哪里的 SSCCE
    猜你喜欢
    • 2011-02-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-12-07
    相关资源
    最近更新 更多