如何解决在 C++ 中按值传递:为什么当我返回主函数时可迭代值会改变?
我正在尝试打印用户从当前地图定义的人口:
我的问题是,当我将它返回到主函数时,为什么迭代的值会改变?
#include <iostream>
#include <string>
#include <map>
std::map<std::string,int> :: iterator get_population(std :: string state,std::map<std::string,int> populationMap)
{
std::map<std::string,int> :: iterator iter;
iter = populationMap.find(state);
// Debug statement
std::cout << "Population is : " << iter -> second;
return iter;
}
int main()
{
std::map<std::string,int> populationMap;
populationMap.insert({{"Mahrashtra",124945748 },{"Uttar Pradesh",223897418},{"Bihar",121741741},{"West Bengal",91276115}});
std::string state = "";
std::cout << "Enter the state who's population you want to find : \n";
std::cin >> state;
// defining a new iterable which stores return from get_population
std::map<std::string,int> :: iterator iter;
iter = get_population(state,populationMap);
std::cout << "The current population of " + state + " is : ";
std::cout << iter->second;
}
它给了我以下输出: 输入您要查找的人口的州: 马哈拉施特拉邦 人口为:124945748 马哈拉施特拉邦当前人口为:1769234796
如果我选择另一个像比哈尔邦这样的键,它工作得很好,但它对马哈拉施特拉邦的工作方式不同。任何帮助将不胜感激
解决方法
您正在按值将地图传递给 get_population
。
查找发生在地图的副本上,您将一个迭代器返回到该副本(当 get_population
返回时该副本被销毁)。
将您的代码更改为如下所示:
std::map<std::string,int> :: iterator get_population(std :: string state,const std::map<std::string,int> & populationMap)
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。