介于多重映射和向量之间的数据结构
可能的重复:
一个 std::map 跟踪顺序插入?
我正在寻找一个像 std::multimap 一样工作的 STL 容器,但我可以像向量一样按插入顺序访问成员。
例如:
multimap<char,int> mymultimap;
multimap<char,int>::iterator it;
mymultimap.insert ( pair<char,int>('a',100) );
mymultimap.insert ( pair<char,int>('z',150) );
mymultimap.insert ( pair<char,int>('b',75) );
mymultimap.insert ( pair<char,int>('a',75) );
for ( it=mymultimap.begin() ; it != mymultimap.end(); it++ )
cout << (*it).first << " => " << (*it).second << endl;
输出:
a => 100个
=> 75
b => 75
z => 150
预期输出:
a => 100z
=> 150
b => 75
一个=> 75
谢谢。
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
您可以使用 std::vector; > 为此。另外,您可以使用 std::make_pair 函数来创建配对。这是示例代码:
You can use
std::vector<std::pair<char,int> >
for this. Also, you can usestd::make_pair
function to create a pair. Here is the sample code:boost 库有一个灵活的多索引容器,可以执行您想要的操作以及更多操作: http://www.boost.org/doc/libs/1_43_0/libs/multi_index/doc/index.html
你可以构建可以顺序访问但也允许 O(log (N)) 快速查找。一开始语法有点不透明,但是一旦你得到了一些东西,这是一项值得的投资,因为该实现将经过 boost 人员和大量普通用户的彻底测试。
The boost libraries have a flexible multiple index container that does what you want and more: http://www.boost.org/doc/libs/1_43_0/libs/multi_index/doc/index.html
You can construct multi_index containers that can be accessed sequentially but also allow O(log(N)) fast lookup. The syntax is a little opaque to start off with, but once you get something working it's a worthwhile investment as the implementation will have been thoroughly tested by the boost guys and a large number of general users.
除了
std::vector 之外>
正如已经建议的,也许 boost::bimap 对您来说是一个很好的解决方案。Other than a
std::vector<std::pair<char,int> >
as already suggested, maybe boost::bimap would be a good solution for you.您可以将
multimap
与list
结合起来。下面是一个可以执行您想要的操作的容器。对象存储在
multimap
中,附加的list
存储 multimap 迭代器(只要指向的元素位于容器中,它们就保持有效)。所有操作都具有与multimap
中相同的复杂性,但erase
方法除外,该方法的复杂度为 O(n*m),其中 n是所有元素的数量,m 是删除的元素数量。如果按插入顺序迭代元素比按键查找更频繁地使用,那么“镜像”这个想法会更优化:将键/值对存储在
list
中(这样我们就可以在插入中迭代order)并具有额外的包含list
元素迭代器的 multiset(用于按键查找目的)。You can combine
multimap
withlist
.Below is a container that do what you want. Objects are stored in a
multimap
and additionallist
stores multimap iterators (they stay valid as long as pointed element is in the container). All operations have the same complexity like inmultimap
excepterase
methods which are O(n*m) where n is number of all elements and m is number of elements removed.If iterating elements in insertion order is more intensively used then lookup by a key then it would be more optimal to "mirror" the idea: store key/value pairs in a
list
(so we can iterate in insertion order) and have additionalmultiset
containing iterators tolist
elements (for by-key-lookup purposes).