gpt4 book ai didi

c++ - 迭代 std::map> 并对 vector 进行排序

转载 作者:塔克拉玛干 更新时间:2023-11-03 01:16:21 27 4
gpt4 key购买 nike

遍历 std::map<X,std::vector<Y> > 时,我可以对 vector 进行排序,还是可以使迭代器无效?

也就是说,下面的代码可以吗?

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());
}

最佳答案

您的代码没问题。 map 中的迭代器只有在您从 map 中删除元素时才会失效。修改 STL 容器的元素永远不会使该容器的迭代器失效,只会对容器本身进行操作,例如删除或有时添加元素。

关于c++ - 迭代 std::map<X,std::vector<Y>> 并对 vector 进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4268734/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com