Home > database >  Why doesn't sorting work for an iterator in Map
Why doesn't sorting work for an iterator in Map

Time:11-20

So here is my code, I find the sort doesn't work for the vector in this map. Does anyone has the idea? The output of this code is still "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]<<" ";
}

CodePudding user response:

You need to use a referenced type in the range based for loop

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.

If your compiler supports the C 17 you can also write

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

//...

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

CodePudding user response:

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 takes a reference to an element of values which allows you to change the contents of values

  • Related