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

0 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;

}
Run Code Online (Sandbox Code Playgroud)

产量

Mar*_*ica 5

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

for (auto x : m)
Run Code Online (Sandbox Code Playgroud)

相当于:

for (std::map<int,int>::value_type x : m)
Run Code Online (Sandbox Code Playgroud)

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

for (auto& x : m)
Run Code Online (Sandbox Code Playgroud)

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

for (std::map<int,int>::value_type& x : m)
Run Code Online (Sandbox Code Playgroud)

  • 对于中等数量的受虐狂,`for(std :: map <int,int> :: reference x:m)` (2认同)