简体   繁体   English

将对象引用转换为STL迭代器

[英]Convert object reference to STL iterator

I am using std::multimap<> and I pass pointer to an element (T*) to a component written in C. 我正在使用std :: multimap <>,并且将指向元素(T *)的指针传递给用C编写的组件。

When the component wants to delete the object it calls back to C++ supplying the pointer, however, I am not sure whether there is a way to convert T* into std::multimap<>::iterator so that I can call erase(). 但是,当组件要删除对象时,它会回调C ++提供指针,但是我不确定是否有将T *转换为std :: multimap <> :: iterator的方法,以便可以调用delete() 。

Any ideas? 有任何想法吗?

If you can determine the key from the item, you can use equal_range to get all the possible matches, then call find on that range. 如果可以从项目中确定键,则可以使用equal_range获取所有可能的匹配项,然后在该范围内调用find。

If there isn't a way to get from an item to it's key (rare but possible), then one could enumerate through the whole multimap (from begin() to end()) and erase the one that matches. 如果没有一种方法可以从某项获取到它的键(稀有但可行),则可以枚举整个multimap(从begin()到end())并擦除匹配的项。 Hopefully this would be a rare operation, as it is O(N). 希望这将是一个罕见的操作,因为它是O(N)。

Do not confuse pointers and iterators. 不要混淆指针和迭代器。 Sometimes (eg arrays) a pointer can function as iterator. 有时(例如数组)指针可以充当迭代器。 But it doesn't necessarily. 但这并不一定。

Iterators in C++ will usually overload the * operator aka "dereference operator". C ++中的迭代器通常会将*运算符(也称为“解除引用运算符”)重载。 This makes them look like C pointers even more, when they technically may or may not be the same. 当它们在技术上可能相同或不同时,这会使它们看起来更像C指针。

Passing iterators is in general fragile, and I'd avoid this. 传递迭代器通常很脆弱,我会避免这种情况。 In particular, a concurrent modification of the multimap in your case may render the iterator invalid. 特别是,在您的情况下并发修改多图可能会使迭代器无效。

Remember that a multimap is a set of key-value pairs. 请记住,多图是一组键值对。 It sounds like your T* is a value and you need an efficient way to get its key so you can remove it. 听起来您的T*是一个 ,您需要一种有效的方法来获取其密钥,以便将其删除。 Have you considered Boost.Bimap ? 您考虑过Boost.Bimap吗? That library allows efficient mappings both ways. 该库允许双向有效映射。 Then it should be simple to take the T* from the calling code, lookup the key, and erase it. 然后,应该很简单地从调用代码中获取T* ,查找密钥,然后将其擦除。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM