简体   繁体   English

迭代std :: map <X,std::vector<Y> &gt;并对矢量进行排序

[英]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? 迭代std::map<X,std::vector<Y> > ,我可以对向量进行排序,还是可能使迭代器失效?

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. 只有从map中删除元素时, 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. 修改STL容器的元素永远不会使该容器的迭代器无效,只会对容器本身进行操作,例如删除或有时添加元素。

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. 作为事实上,你不应该有任何疑问,你是从既没有插入,也不删除元素map :在结构map是不变的,你只是影响存储的值。

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. 这里有一些错误的信息,因此会在.std :: maps中有一些特殊之处在于你可以在不使现有迭代器失效的情况下插入新元素,并且删除元素只会使对该特定元素的任何迭代器无效。 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 引用SGI STL页面: 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. Map具有重要的属性,即将新元素插入到映射中不会使指向现有元素的迭代器无效。 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. 正如aschepler所说,你的代码很好。 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. 因此,您可以更改矢量内的值而不会影响地图。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM