哪个 STL 容器用于存储具有基于密钥的访问的有序数据?
假设我有一个 Person 对象的集合,每个对象如下所示:
class Person
{
string Name;
string UniqueID;
}
现在,这些对象必须存储在一个容器中,该容器允许我对它们进行排序,以便我可以给项目 X 轻松找到项目 X+1 和 X-1 。
但是,我还需要基于 UniqueID 的快速访问,因为集合很大,线性搜索无法解决。
我当前的“解决方案”是将 std::list 与 std::map 结合使用。该列表保存 Persons(用于有序访问),并且映射用于将 UniqueID 映射到对列表项的引用。更新“容器”通常涉及更新地图和列表。
它有效,但我觉得应该有一种更聪明的方法来做到这一点,也许是 boost:bimap
。建议?
编辑:我对“订购”的要求有些混乱。解释一下,对象是从文件中按顺序流入的,并且容器中项目的“顺序”应与文件顺序匹配。该顺序与 ID 无关。
Let's say I have a collection of Person objects, each of which looks like this:
class Person
{
string Name;
string UniqueID;
}
Now, the objects must be stored in a container which allows me to order them so that I can given item X easily locate item X+1 and X-1.
However, I also need fast access based on the UniqueID, as the collection will be large and a linear search won't cut it.
My current 'solution' is to use a std::list in conjunction with a std::map. The list holds the Persons (for ordered access) and the map is used to map UniqueID to a reference to the list item. Updating the 'container' typically involves updating both map and list.
It works, but I feel there should be a smarter way of doing it, maybe boost:bimap
. Suggestions?
EDIT: There's some confusion about my requirement for "ordering". To explain, the objects are streamed in sequentially from a file, and the 'order' of items in the container should match the file order. The order is unrelated to the IDs.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
boost:bimap
是最明显的选择。bimap
基于boost::multi_index
,但bimap
简化了语法。就我个人而言,我更喜欢boost::multi_index
而不是boost::bimap
,因为它允许将来轻松地向Person
结构添加更多索引。boost:bimap
is the most obvious choice.bimap
is based onboost::multi_index
, butbimap
has simplified syntax. Personally I will preferboost::multi_index
overboost::bimap
because it will allow to easily add more indices to thePerson
structure in the future.没有标准库容器可以满足您的需求 - 因此您必须使用两个容器或 Boost 解决方案。如果使用两个容器,在几乎所有情况下,我通常更喜欢向量或双端队列而不是列表。
There is no Standard Library container that does what you want - so you will have to use two containers or the Boost solution. If using two containers, I would normally prefer a vector or a deque over a list, in almost all circumstances.
为什么不使用两张地图,一张以 Person 作为键,另一张以 UniqueId 作为键,但这需要更新它们。
您可以创建一个回调函数,每当有任何变化时都会更新两个地图。
Why not to use two maps , one having Person as Key and another one having UniqueId as Key, but that requires updating both of them.
you can create a callback function which updates both the maps whenever there is any change.