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

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

#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 returns 正确的行数但使用 get_second returns 没有元素的新地图元素。 这种行为的原因是什么?

我在 Ubuntu.

上使用 g++ 5.3.1

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

你的 get_second 方法参数在常量方面与循环迭代器不匹配...更新如下(注意成对的常量字符串)并且它有效:

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

get_second 取了一对错误的类型,带有非 const 键。

因此构造了一个转换后的临时文件,您将返回对此临时文件的引用。

之后所有赌注都取消了。

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

您只需更改为 get_second(const nfa::value_type& p) 即可获得正确的行为。