【问题标题】:Why the value in Map of STL is not changing?为什么 STL 的 Map 中的值没有变化?
【发布时间】:2018-05-22 11:57:39
【问题描述】:

如果值大于 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;

}

【问题讨论】:

  • for(auto x: m) 更改为 for(auto &amp;x: m) 它正在制作副本,然后您正在更改副本的值而不是原始值。
  • @RichardCritten 发表您的评论作为答案

标签: c++ dictionary stl


【解决方案1】:

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)

【讨论】:

  • 对于中等程度的受虐狂,for (std::map&lt;int, int&gt;::reference x : m)
猜你喜欢
  • 2018-04-28
  • 2022-10-07
  • 2015-11-26
  • 2011-07-05
  • 2018-04-02
  • 2018-02-06
  • 2013-06-03
  • 2017-03-16
  • 1970-01-01
相关资源
最近更新 更多