简体   繁体   中英

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.

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().

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.

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. Hopefully this would be a rare operation, as it is 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". This makes them look like C pointers even more, when they technically may or may not be the same.

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. Have you considered 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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