【问题标题】:Passing map by reference in C++ and mutating its value在 C++ 中通过引用传递 map 并改变它的值
【发布时间】:2021-09-11 04:33:04
【问题描述】:

我在 canSum 函数中通过引用传递 map,我正在改变它的值并添加对,但最后当我迭代 map 时,我发现 map 的值没有更新。

canSum 函数是一个递归函数,它接受一个数字(targetSum)和一个数组,并判断是否可以通过数组中的任何数字组合(数字可以重复)来形成 targetSum。

#include<iostream>
#include<vector>
#include<map>

using namespace std;

bool canSum(int targetSum,vector<int> a,map<int, bool> &m){
  if(!(m.find(targetSum) == m.end()))
    return m[targetSum];
  if (targetSum == 0)
    return true;
  if(targetSum<0)
    return false;

  for (int num : a)
  {
    
    if (canSum(targetSum - num, a,m)==true)
    {
      
      // m[targetSum] = true;
      m.insert(pair<int, bool>(targetSum, true));
      return m[targetSum];
    }
  }
  m[targetSum] = false;
  return m[targetSum];
}

int main(){
  int targetSum, t;
  vector<int> a;
  map<int, bool> m;
  m[0] = true;
  cout << "enter target" << endl;

  cin >> targetSum;
  cout << "enter array, press esc to stop entering"<<endl;
  while(cin>>t){
    a.push_back(t);
  }

  for (int j = 0; j < a.size(); j++)
  {
    cout << a[j]<<" ";
  }

  cout << endl;

  for (auto itr = m.begin(); itr != m.end(); ++itr) {
        cout << '\t' << itr->first
             << '\t' << itr->second << '\n';
    }

  if(canSum(targetSum, a,m)){
    cout << endl << "true" << endl;
  }
  else cout << endl << "false" << endl;
  
  return 0;
}

请帮助我。谢谢。

【问题讨论】:

  • 一开始为什么要检查m.find(1)
  • 应该是 m.find(targetSum)。我已经纠正了。感谢您指出。附言。这不会影响我面临的问题。
  • "当我遍历 map 时,我发现 map 的值没有更新"不清楚你从哪里得出这个结论。请张贴minimal reproducible example,它会打印出意想不到的东西,并说明您希望打印的内容。
  • 我在调用函数之前就调用了 for 循环来打印地图。因此,对我来说,地图并没有发生变异。 2年后我才重新开始编码。我为愚蠢的错误道歉。

标签: dictionary stl c++17 pass-by-reference


【解决方案1】:

打印地图的for循环应该在函数调用之后。

if(canSum(targetSum, a,m)){
    cout << endl << "true" << endl;
}
else cout << endl << "false" << endl;

for (auto itr = m.begin(); itr != m.end(); ++itr) {
    cout << '\t' << itr->first
    << '\t' << itr->second << '\n';
}

代替

for (auto itr = m.begin(); itr != m.end(); ++itr) {
    cout << '\t' << itr->first
    << '\t' << itr->second << '\n';
}

if(canSum(targetSum, a,m)){
    cout << endl << "true" << endl;
}
else cout << endl << "false" << endl;

查看地图中因函数而发生的突变

【讨论】:

    猜你喜欢
    • 2019-11-28
    • 2015-05-19
    • 2014-07-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多