C++ c++;一种高效的双向随机存取数据结构

C++ c++;一种高效的双向随机存取数据结构,c++,data-structures,map,C++,Data Structures,Map,我有两个集合a和b的元素a和b。现在它们相互关联(0..1:n基数),因此每个a在b中最多有一个伙伴,每个b可以有几个(至少一个)关联到a中的项。 A是一组整数对,B是整数 有没有有效的方法来存储这样的“双向”地图? 一种简单的方法是使用两种地图: map<pair<unsigned int, unsigned int>, unsigned int> AtoB map<unsigned int, vector<pair<unsigned int, uns

我有两个集合a和b的元素a和b。现在它们相互关联(0..1:n基数),因此每个a在b中最多有一个伙伴,每个b可以有几个(至少一个)关联到a中的项。 A是一组整数对,B是整数

有没有有效的方法来存储这样的“双向”地图? 一种简单的方法是使用两种地图:

map<pair<unsigned int, unsigned int>, unsigned int> AtoB
map<unsigned int, vector<pair<unsigned int, unsigned int> > > BtoA
映射AtoB
地图BtoA
但也许有更好的方法来更有效地处理这个问题


感谢您的帮助

如何
boost::bimap
?我想这是为您准备的。

Boost包含两个库来处理这个问题:和。前者专门针对双射(“双向”)映射的问题,而第二个更一般,实现了类似于具有任意索引的内存中数据库的功能

考虑到
unsigned int
键不能唯一地映射到对,我认为多索引更合适。我已经很长时间没有使用这个库了,但是看看教程,您可能需要

struct YourData {
     unsigned key;
     std::pair<unsigned, unsigned> value;
};

typedef multi_index_container<
    YourData,
    indexed_by<
        ordered_non_unique<member<YourData, unsigned, &YourData::key> >,
        ordered_unique<member<YourData, std::pair<unsigned, unsigned>,
                              &YourData::value> >
    >
> YourContainer;
struct YourData{
无符号密钥;
std::对值;
};
typedef多索引容器<
你的数据,
索引<
有序非唯一,
有序_唯一
>
>你的容器;
如果您不想使用Boost,那么您至少可以通过替换

map<unsigned int, vector<pair<unsigned int, unsigned int> > >
map

通过
std::multimap
映射,multimap的效率为O(logn),因此,我认为这是存储数据的最佳方式。我建议使用

map<pair<unsigned int, unsigned int>, unsigned int> AtoB
multimap<pair<unsigned int, unsigned int>, unsigned int> BtoA
映射AtoB
多映射BtoA