按值删除地图元素

发布于 2024-07-23 11:36:58 字数 189 浏览 1 评论 0原文

我会保持简短。

我试图在字符串和对象指针之间保留映射,因此,我使用 std::map。 我有一个管理器,它是一个全局类,用于跟踪映射,每当调用对象的析构函数时,它都会告诉管理器它已被删除。

我能想到的唯一方法就是在地图中搜索该对象。 有没有有效的STL解决方案来解决这个问题? 是否也存在能够有效按键搜索的地图?

I'll keep this brief.

I am trying to keep a map between strings and object pointers, and as such, I use std::map. I have a manager that's a global class that keeps track of the map, and whenever an object's destructor is called, it tells the manager that it has been deleted.

The only way I can think of is to search through the map for the object. Is there an efficient STL solution to this problem? Does a map that is efficient at searching by key as well exist?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

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

发布评论

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

评论(3

扎心 2024-07-30 11:36:58

不,除了通过比较值进行迭代之外,没有一种有效的方法可以使用 std::map 来执行此操作。

然而,大多数时候,值的键可以从值本身计算出来。 例如,使用 Person 对象的 Name 属性作为键。 管理器是否可以存储键/值对列表而不是值本身。 这将解决您的问题,而无需重写新算法。

或者,您可以在管理器类上保留反向映射。 本质上是值到键。 这样您就可以使用它来计算稍后要删除的密钥。

No there is not an efficient way of doing this with std::map other than iterating through comparing the values.

However most of the time the key for a value is computable from the value itself. For example using the Name property of a Person object as the key. Is it possible for the manager to store a list of key / value pairs as opposed to the value itself. This would solve your problem without having to rewrite a new algorithm.

Or alternatively you could keep a reverse map on the manager class. Essentially value to key. That way you could use it to compute the key to remove later on.

穿透光 2024-07-30 11:36:58

查看SGI 的 STL 文档

地图有一个重要的属性:
将新元素插入到地图中
不会使迭代器无效
指向现有元素。 擦除
地图中的元素也不
使任何迭代器无效,除了
当然,对于实际上的迭代器
指向正在存在的元素
已删除。

因此,您可以将迭代器存储到对象内部的映射中,并在需要删除其条目时将其用作常量时间查找键。

Looking at SGI's documentation for the STL,

Map has the important property that
inserting a new element into a map
does not invalidate iterators that
point to existing elements. Erasing an
element from a map also does not
invalidate any iterators, except, of
course, for iterators that actually
point to the element that is being
erased.

So you can store an iterator into the map inside your object, and use that as a constant-time lookup key when you need to go delete its entry.

江湖彼岸 2024-07-30 11:36:58

查看 Boost 多索引容器 图书馆。

Take a look at Boost Multi-Index Containers library.

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