【问题标题】:Pass by value in c++ :Why is the iterable value changing when I'm returning to main function?在 c++ 中按值传递:为什么当我返回主函数时可迭代值会发生变化?
【发布时间】:2021-07-12 07:17:57
【问题描述】:

我正在尝试打印用户从当前地图定义的人口:

我的问题是为什么当我将 iterable 返回给 main 函数时它的值会发生变化?

     #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

如果我选择像比哈尔这样的另一个键,它工作得很好,它只对马哈拉施特拉邦有不同的作用。任何帮助将不胜感激

【问题讨论】:

  • 您通过值传递populationMap,因此get_population 中的iterpopulationMap 的本地副本相关联,并在返回时变为无效。尝试通过 const 引用传递 populationMap

标签: c++ stl iterator maps


【解决方案1】:

您正在将地图按值传递给get_population

查找发生在地图的副本上,并且您将一个迭代器返回到该副本中(当get_population 返回时被销毁)。

将您的代码更改为如下所示:

std::map<std::string , int> :: iterator get_population(std :: string state , const std::map<std::string , int> & populationMap)

【讨论】:

  • 但它在比哈尔邦工作就没有意义了,对吧?
  • @KhushiRajpal 严格来说,由于使用了无效的迭代器,您问题中的代码表现出未定义的行为。在这种情况下,任何事情都可能发生——包括它似乎在某些情况下起作用。
猜你喜欢
  • 2011-09-30
  • 2019-09-19
  • 2013-07-02
  • 1970-01-01
  • 2015-10-16
  • 2017-05-29
  • 2018-07-21
  • 2013-07-30
  • 2013-11-12
相关资源
最近更新 更多