When iterating over std::map<X,std::vector<Y> >
, may I sort the vectors, or might that invalidate the iterator?
In other words, is the following code okay?
typedef std::map<int, std::vector<int> > Map;
Map m;
for (Map::iterator it = m.begin(); it != m.end(); ++it) {
std::sort(it->second.begin(), it->second.end());
}
Your code is okay. Iterators from a map
are only invalidated when you remove elements from the map. Modifying an element of an STL container never invalidates that container's iterators, only operations on the container itself, like removing or sometimes adding elements.
Your code is perfectly fine. As a matter of fact, you shouldn't have any doubt as you are neither inserting nor removing elements from the map
: the structure of the map
is unchanged, you are only affecting the values stored.
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