简体   繁体   English

C ++中的稀疏数组

[英]Sparse array in C++

I need a vector-like container, with integer indexation, but where some indices are omitted. 我需要一个类似矢量的容器,带有整数索引,但是省略了一些索引。 So what is the common way to represent such sparse array in C++? 那么在C ++中表示这种稀疏数组的常用方法是什么? I have an intuition that std::map is mostly used for such purposes. 我有一种直觉,即std :: map主要用于此类目的。 But it is rather slow for container where new items aren't usually added. 但对于通常不添加新物品的容器来说,这是相当缓慢的。 What can you propose? 你能提出什么建议?

UPD: Not very "sparse". UPD:不是很“稀疏”。 Maybe about 5%. 也许大约5%。 Items mostly added during initialization step (and not very often after). 项目主要在初始化步骤期间添加(并且通常不会在之后)。 But access is frequent (obviously I would not start this topic, if it was not crucial). 但访问频繁(显然我不会开始这个话题,如果它不重要)。

Yes, a map is usually the correct approach. 是的,地图通常是正确的方法。

I would suggest a C++11 unordered_map (based on hash tables) to get lightning-fast lookup: it's pretty much the best you can do without a contiguous incrementing key. 我建议使用C ++ 11 unordered_map (基于哈希表)来获得快速查找:如果没有连续的递增密钥,它几乎是最好的。

Maybe something like 也许是这样的

std::vector<boost::optional<your_type>> 

would be enough for you. 对你来说已经足够了。

Items mostly added during initialization step (and not very often after). 项目主要在初始化步骤期间添加(并且通常不会在之后)。 But access is frequent 但访问频繁

In this case boost::container::flat_map can be a good option for you. 在这种情况下, boost :: container :: flat_map对你来说是个不错的选择。 It is basically just a sorted vector. 它基本上只是一个有序矢量。 Advantages (stolen from the website): 优点(从网站上窃取):

  • Faster lookup than standard associative containers 比标准关联容器更快的查找
  • Much faster iteration than standard associative containers 迭代比标准关联容器快得多
  • Less memory consumption for small objects (and for big objects if shrink_to_fit is used) 小对象(如果使用shrink_to_fit,对于大对象)的内存消耗更少
  • Improved cache performance (data is stored in contiguous memory) 改进的缓存性能(数据存储在连续的内存中)

A potential drawback: 潜在的缺点:

  • Worst case linear-time insertions and linear-time deletions 最坏情况线性时间插入和线性时间删除

Even if the worst case happens during insertion or deletion (moving elements of the underlying vector), it is still not that bad thanks to (1) the good use of the cache, (2) relocation of the underlying elements may be vectorized (vector instructions). 即使最坏的情况发生在插入或删除期间(移动底层矢量的元素),由于(1)缓存的良好使用,它仍然没有那么糟糕,(2)底层元素的重定位可以被矢量化(矢量)说明)。 You would have to try it in your application to see if insertion / deletion is a problem, given your usage pattern. 根据您的使用模式,您必须在应用程序中尝试插入/删除是否存在问题。

If flat_map is not suitable for you, I would try std::unordered_map . 如果flat_map不适合你,我会尝试std::unordered_map

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM