开发者

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 开发者_StackOverflow社区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.


Some misinformation here, so will chip in. std::maps are kind of special in that you can insert new elements without invalidating existing iterators, and removing an element only invalidates any iterators to that specific element. Given an iterator into the map, you may not modify the key (otherwise the sort order would be corrupted - one of the container's invariants), but you may modify the values however you like. Your array sorting falls into this last category of operation, and is perfectly fine.

To quote from the SGI STL page: http://www.sgi.com/tech/stl/Map.html

Map has the important property that inserting a new element into a map does not invalidate iterators that point to existing elements. Erasing an element from a map also does not invalidate any iterators, except, of course, for iterators that actually point to the element that is being erased.


As aschepler says, your code is fine. I'd only add that there is a distinction between a vector which the map has as its target and the values inside any of the vectors. Because of this, you can change the values inside the vectors without affecting the map.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜