从函数返回时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返回正确的行数,但使用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_map
的value_type
是std::pair<const Key, T>
(它是const Key),所以你的get_second()
的参数是错误的。
您可以简单地更改为get_second(const nfa::value_type& p)
以获得正确的行为
相关文章:
- 将从std::映射中获取的std::pair引用传递给接受std::对引用的函数
- pair的两个构造函数几乎相同,为什么不生成构建错误?
- 类模板的参数太少 "std::pair":在函数中将 std 对作为参数传递
- C++ vector<pair<int,int>> std::all_of() 函数问题(重定向到头文件)
- 接收std :: Pair作为参数并从支撑列表初始化中推论的模板函数
- 在函数调用中使用类型vector<pair<int,int>>::iterator&in
- C++错误处理-使用std::pair或std::tuple返回错误代码和函数返回的缺点
- 如何在不复制的情况下将只读向量传递给作为<int> pair<int,int>向量一部分的函数
- 谷歌模拟成员函数中的std::pair参数编译失败
- 如果我使用函数指针作为一对的值,我会遇到stl::pair问题2051吗
- std::pair的默认构造函数<>将基本类型(int等)设置为零
- std::pair正在为其成员之一调用默认构造函数
- [C++ STL]-pair<vector-iter,int*> - 不匹配 - 无匹配函数
- 将指向成员函数的指针绑定到std::pair并强制转换为void*
- 不包括使用显式构造的std::pair构造函数
- 为什么在c++ 11中将std::pair类标准更改为不允许只有非常量复制构造函数的类型?
- 如何从函数返回pair
- vector<pair<int,unordered_set<int>>> 在为对提供默认构造函数参数时给出分段错误
- 对一对整数(pair
)向量的哈希函数 - Std::pair:过于严格的构造函数