Warm tip: This article is reproduced from stackoverflow.com, please click
c++ c++11 auto

Why doesn't range-based for loop modifiy container elements?

发布于 2020-03-27 10:24:13

I recently observed that modifying data inside a auto iterated vector is not yielding correct results for me. For example when i tried to sort elements of vector of vector, some elements were not sorted but the code ran successfully

vector<vector<int> > arr;
arr.push_back({38, 27});
for(auto v : arr)
{
    sort(v.begin(), v.end());
}

The output of above code after sorting is still 38, 27 after sorting. Whereas when i sort as sort(arr[0].begin(), arr[0].end()), the result is correct. I compiled using gcc.

Questioner
Kshitij Shukla
Viewed
110
Demosthenes 2019-07-03 22:41

Your for loop copies v, then sorts it. The original is untouched. What you want is for (auto &v : arr).