Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Iterating over std::map<X,std::vector<Y> > and sorting the vectors

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());
}
like image 313
Frank Avatar asked Dec 29 '22 04:12

Frank


2 Answers

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.

like image 199
aschepler Avatar answered Dec 30 '22 16:12

aschepler


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.

like image 30
icecrime Avatar answered Dec 30 '22 18:12

icecrime