用于双向随机访问的 C++ 高效数据结构
c++ efficient data structure for bidirectional random access
我有两组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
但也许有很好的方法来更有效地处理这个问题。
感谢您的帮助
Boost
包含两个库来处理这个问题:Boost.Bimap 和 Boost.MultiIndex。前者特定于双射("双向")映射的问题,而后者则更通用,实现了类似于具有任意索引的内存数据库的东西。
鉴于您的unsigned int
键不能唯一映射到您的对,我认为 MultiIndex 更有序。自从我上次使用这个库以来已经有很长时间了,但是查看教程,您将需要类似的东西
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;
如果您不想使用 Boost,那么您至少可以通过替换
map<unsigned int, vector<pair<unsigned int, unsigned int> > >
通过一个std::multimap<unsigned, std::pair<unsigned, unsigned>>
.
boost::bimap
怎么样? http://www.boost.org/doc/libs/1_47_0/libs/bimap/doc/html/index.html 我认为这是给你的。
Map 和 Multimap 的效率为 O(log n),因此,我认为这是存储数据的最佳方式。我建议使用
map<pair<unsigned int, unsigned int>, unsigned int> AtoB
multimap<pair<unsigned int, unsigned int>, unsigned int> BtoA
相关文章:
- C++中高效的大型稀疏块压缩线性方程
- C++中的高效循环缓冲区,它将被传递给C样式数组函数参数
- 如何在C++中高效地构造随机骰子
- 如何实现高效的算法来计算大型数据集的多个不同值?
- 更高效地在微控制器上对C++进行基准测试
- 从C++无序集合中高效提取元素
- 高效的字符串截断算法,按顺序删除相等的前缀和后缀
- C++中特征对角矩阵类型的高效存储
- 高效简单的结构比较运算符
- 使用 Rcpp 的高效矩阵子集
- C++ 包含特征矩阵的类的高效算术运算符重载
- CUDA 高效的 nd-array(张量)切片
- 大多数基本类型的高效二进制序列化
- RAM高效C++属性
- 如何为球形物体和三角形地形提供高效的碰撞检测和响应
- 如何实现四个 i8 元素组的高效_mm256_madd_epi8点积
- 如何在嵌套映射(C++)中高效地查找密钥
- 在C++中高效地保存许多连续记录的图像
- C++ - 将函数链接到触发器的有效和高效方法
- C/C++ 中的高效 pcap 解析器