简体   繁体   English

为什么 Map 中的迭代器排序不起作用

[英]Why doesn't sorting work for an iterator in Map

So here is my code, I find the sort doesn't work for the vector in this map.所以这是我的代码,我发现排序不适用于这个 map 中的向量。 Does anyone has the idea?有没有人有这个想法? The output of this code is still "3 1 2 4 5"此代码的 output 仍然是“3 1 2 4 5”

map<int, vector<int> > values;
values[1] = {3,1,2,4,5};
for(auto g: values) {
    sort(g.second.begin(), g.second.end());
}
for(int i=0;i<values[1].size();i++) {
    cout<<values[1][i]<<" ";
}

You need to use a referenced type in the range based for loop您需要在基于范围的 for 循环中使用引用类型

for(auto &g: values) {
    sort(g.second.begin(), g.second.end());
}

Otherwise the range based for loop deals with copies of elements stored in the map.否则,基于范围的 for 循环处理存储在 map 中的元素的副本。

If your compiler supports the C++ 17 you can also write如果你的编译器支持 C++ 17 你也可以写

#include <vector>
#include <map>
#include <iterator>
#include <algorithm>

//...

for (auto &[key, v] : values)
{
    std::sort( std::begin( v ), std::end( v ) );
}

auto g: values takes the value of an element of values but does not allow you to change the contents in values . auto g: values获取values 但不允许您更改values中的内容。

auto &g: values takes a reference to an element of values which allows you to change the contents of values auto &g: values引用values的元素,它允许您更改values的内容

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

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