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

标签 c++ dictionary stl

如果值大于 1,我将 map(Key-Value pair) 中的值减 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

最佳答案

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

for (auto x : m)

相当于:

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

这会复制键和值。然后您修改拷贝,实际 map 中的任何内容都没有更改。你需要的是:

for (auto& x : m)

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

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

关于c++ - 为什么STL的Map中的值没有变化?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50467093/

相关文章:

python - 使用 Pandas 将一列字典拆分/分解为单独的列

dictionary - 如何在 cassandra 数据库 2.2.1 中创建嵌套集合 map<text,list<text>> 类型

c++ - 尝试制作 STL map 容器的包装器时出错

c++ - 从 vector 中提取子 vector 的最佳方法?

c++ - CreateFile() 串行通信问题

c++ - ns-3 中的 Waf 配置

python - 调用函数时过滤关键字参数

c++ - 如何在 std::remove_if 之后使用 "removed"元素

C++ libcurl http响应代码问题

c++ - 将 std::cout 添加到全局运算符新掩码 SIGSEGV