为什么STL Map中的值没有变化?

时间:2018-05-22 11:57:39

标签: c++ dictionary stl

如果值大于1,我将map(键值对)中的值减去1

#include <bits/stdc++.h>
using namespace std;
int main()
{
     // Creating a map with 4 element
    map<int,int> m;
    m[1]=1;
    m[2]=2;
    m[3]=1;
    m[4]=3;
     //Printing the output
    for(auto x: m)cout<<x.first<<" "<<x.second<<endl;
    //Applying substraction
    for(auto x: m)
    {
        if(x.second>1)
        {
            x.second--;
        }
    }
    cout<<"After subtraction operation: \n";
    for(auto x: m)cout<<x.first<<" "<<x.second<<endl;

}

Output

1 个答案:

答案 0 :(得分:5)

auto使用与模板相同的类型推导规则,它们支持值类型,而不是引用类型。所以:

for (auto x : m)

相当于:

for (std::map<int,int>::value_type x : m)

这会生成密钥和值的副本。然后,您可以修改副本,并且实际地图中的任何内容都不会更改。你需要的是:

for (auto& x : m)

(或者,如果你真的是受虐狂):

for (std::map<int,int>::value_type& x : m)
相关问题