Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to remove multiple items from unordered map while iterating over it?

Tags:

People also ask

How do you delete a map while iterating?

You should always use Iterator's remove() method to remove any mapping from the map while iterating over it to avoid any error. Use of Map. remove() method is prohibited during traversal because it throws ConcurrentMdoficiationException.

How do you delete an unordered map value?

erasing by key: It takes a key as a parameter and erases the key and value. unordered_map. erase(const key); erase by range: It takes two iterators as a parameter and erases all the key and values present in between (including the starting iterator and excluding the end iterator).

Can you iterate over unordered_map?

Iterating over a map by using STL Iterator: By creating an iterator of std::map and initializing it to the starting of map and visiting upto the end of map we can successfully iterate over all the elements of map.

Which is faster map or unordered map?

For the unordered_map + map , it takes 70 ms for unordered_map insertion and 80 ms for map insertion. So the hybrid implementation is 50 ms faster. We should think twice before we use the map . If you only need the data to be sorted in the final result of your program, a hybrid solution may be better.


Please consider the following situation:

using namespace std; unordered_map<int, vector<A>> elements; 

Now I'm iterating over this unordered map:

for (auto it = elements.begin(); it != elements.end(); ++it) 

Inside the loop, I'm forming clusters out of several elements of elements (the current one that it points to and some more, not necessarily those next in line!). Because each element can be only part of one cluster, I'd like to remove those from the map and then continue with the next element (i.e., build the next cluster).

How can I do this and still continue the iteration at the correct position?