从函数返回时std::pair秒的奇怪行为

Weird behavior of std::pair second when returned from a function

本文关键字:pair 函数 返回 std      更新时间:2023-10-16
#include<boost/unordered_map.hpp>
#include<string>
#include<iostream>
#include<boost/unordered_set.hpp>
using namespace std;
typedef boost::unordered_map<string, boost::unordered_map<string,     boost::unordered_set<string>>> nfa;
const boost::unordered_map<string, boost::unordered_set<string>>&    
get_second(const std::pair<string, 
           boost::unordered_map<string, boost::unordered_set<string>>>& p)
 {return p.second;}

int main()
{
   nfa a;
   a["A"]["0"] = {"B", "C"};
   a["A"]["1"] = {"B"};
   a["B"]["0"] = {"B"};
   a["B"]["1"] =  {"C"};
   cout << "Printing using direct reference" << endl;
   for (auto tr_table : a)
   {
     for (auto tr : tr_table.second)
      cout << tr_table.first << " " << tr.first << " " <<     tr.second.size() << endl;
  }
  cout << "Printing using function get_second" << endl;
  for (auto tr_table : a)
  {
    for (auto tr : get_second(tr_table))
      cout << tr_table.first << " " << tr.first << " " << tr.second.size() << endl;
  }
 return 0;
 }

对于同一个unordered_map,使用tr.second返回正确的行数,但使用get_second返回一个没有元素的新映射元素。这种行为的原因是什么?

我在Ubuntu上使用g++ 5.3.1。

PS:使用std::unordered_map时行为相同

get_second使用的是错误类型的一对,并且具有非const密钥。

因此将构造一个转换后的临时对象,并且返回对该临时对象的引用。

你的get_second方法参数在常量方面与循环迭代器不匹配…更新如下(注意const string in pair),它可以工作了:

get_second( const std::pair<const string,
    unordered_map<string, unordered_set<string>>>& p )

注意std::unordered_mapvalue_typestd::pair<const Key, T>(它是const Key),所以你的get_second()的参数是错误的。

您可以简单地更改为get_second(const nfa::value_type& p)以获得正确的行为