首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >在C++中通过引用传递map并改变其值

在C++中通过引用传递map并改变其值
EN

Stack Overflow用户
提问于 2021-06-29 06:30:07
回答 1查看 33关注 0票数 1

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

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

代码语言:javascript
运行
复制
#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;
}

请帮帮我。谢谢。

EN

回答 1

Stack Overflow用户

发布于 2021-06-29 22:01:40

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

代码语言:javascript
运行
复制
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';
}

而不是

代码语言:javascript
运行
复制
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;

查看由于函数而导致的映射中的突变

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/68170662

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档