【发布时间】:2016-06-29 11:39:26
【问题描述】:
#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 时的行为是相同的。
【问题讨论】:
-
你正在复制很多地图。
-
我并不担心继续复制,但我想了解为什么两个 for 循环的行为不同。有没有办法避免复制?
-
Visual Studio 在 in 内部循环中引发迭代器 derferencing 的调试异常。 (使用
std::版本)。 -
对不起,我忘了提,我在 ubuntu 上使用 g++ 5.3.1。
-
@prasannak “有没有办法避免复制?”。对其他循环使用
for( const auto& tr_table : a )和类似的东西
标签: c++ stl unordered-map