简体   繁体   English

在C ++中进行关联和迭代

[英]Associating and iterating in C++

I've got a situation where I want to use an associative container, and I chose to use a std::unordered_map, because it's perfectly feasible that this container could be used to hold millions or more of elements. 我遇到了要使用关联容器的情况,我选择使用std :: unordered_map,因为可以使用该容器容纳数百万或更多的元素是完全可行的。 But now I also need to iterate in order. 但是现在我也需要按顺序进行迭代。 I considered having the value types link to each other in a list, but now I'm going to have issues with memory management. 我考虑过让值类型在列表中相互链接,但是现在我将在内存管理方面遇到问题。

Should I change container, say to a std::map? 我应该更改容器,对std :: map说吗? Or just iterate once through my unordered_map, insert into a vector, and sort, then iterate? 或者只是通过unordered_map迭代一次,插入向量中,然后排序,然后进行迭代? It's pretty unlikely that I will need to iterate in an ordered fashion repeatedly. 我不太可能需要以有序方式反复进行迭代。

You could use Boost.MultiIndex , specifying the unordered (hashed) index as well as an ordered one, on the same underlying object collection. 您可以使用Boost.MultiIndex ,在同一基础对象集合上指定无序(哈希)索引和有序索引。

Possible issues with this - there is no natural mapping from an existing associative container model, and it might be overkill if you don't need the second index all the time. 可能存在的问题-现有关联容器模型没有自然映射,如果您一直不需要第二个索引,则可能会过大。

Well, you know the O() of the various operations of the two alternatives you've picked. 好吧,您知道您选择的两个替代方案的各种运算的O()。 You should pick based on that and do a cost/benefit analysis based on where you need the performance to happen and which container does best for THAT. 您应该基于此进行选择,并根据需要在何处发生性能以及哪个容器最适合THAT进行成本/收益分析。

Of course, I couldn't possibly know enough to do that analysis for you. 当然,我可能不太了解如何为您进行分析。

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

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