哪个 STL 容器用于存储具有基于密钥的访问的有序数据?

发布于 2024-09-08 18:11:22 字数 512 浏览 0 评论 0原文

假设我有一个 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

无边思念无边月 2024-09-15 18:11:22

boost:bimap 是最明显的选择。 bimap 基于 boost::multi_index,但 bimap 简化了语法。就我个人而言,我更喜欢 boost::multi_index 而不是 boost::bimap,因为它允许将来轻松地向 Person 结构添加更多索引。

boost:bimap is the most obvious choice. bimap is based on boost::multi_index, but bimap has simplified syntax. Personally I will prefer boost::multi_index over boost::bimap because it will allow to easily add more indices to the Person structure in the future.

桃气十足 2024-09-15 18:11:22

没有标准库容器可以满足您的需求 - 因此您必须使用两个容器或 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.

够钟 2024-09-15 18:11:22

为什么不使用两张地图,一张以 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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文