按值删除地图元素
我会保持简短。
我试图在字符串和对象指针之间保留映射,因此,我使用 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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
不,除了通过比较值进行迭代之外,没有一种有效的方法可以使用 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.
查看SGI 的 STL 文档,
因此,您可以将迭代器存储到对象内部的映射中,并在需要删除其条目时将其用作常量时间查找键。
Looking at SGI's documentation for the STL,
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.
查看 Boost 多索引容器 图书馆。
Take a look at Boost Multi-Index Containers library.