pra*_*nak 1 c++ stl unordered-map
#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;
}
Run Code Online (Sandbox Code Playgroud)
对于相同的unordered_map,使用tr.second返回正确的行数,但使用get_second会返回一个没有元素的新map元素.这种行为的原因是什么?
我在Ubuntu上使用g ++ 5.3.1.
PS:使用std :: unordered_map时行为相同.
get_second采用一对错误的类型,使用非const密钥.
因此,构造了转换后的临时值,并且您将返回对此临时值的引用.
之后所有的赌注都没有了.