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.
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).
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.
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?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With