在 C++ 中按值传递:为什么当我返回主函数时可迭代值会发生变化?
Pass by value in c++ :Why is the iterable value changing when I'm returning to main function?
我正在尝试打印用户根据当前地图定义的人口:
我的问题是,当我将它返回到主函数时,为什么 iterable 的值会发生变化?
#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
returns 时被销毁)。
将您的代码更改为如下所示:
std::map<std::string , int> :: iterator get_population(std :: string state , const std::map<std::string , int> & populationMap)
我正在尝试打印用户根据当前地图定义的人口:
我的问题是,当我将它返回到主函数时,为什么 iterable 的值会发生变化?
#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
returns 时被销毁)。
将您的代码更改为如下所示:
std::map<std::string , int> :: iterator get_population(std :: string state , const std::map<std::string , int> & populationMap)