在嵌套无序映射中插入或更新密钥

时间:2019-03-29 15:58:19

标签: c++ nested unordered-map

我正在尝试更新嵌套映射中的某个键(如果存在)或插入它(如果不存在)。我正在尝试使用带有lower_bound的迭代器以使此过程高效。

std::unordered_map<std::string, std::unordered_map<std::string, std::string>> maps;
cache::iterator iter(maps[command[1]].lower_bound(command[2]));
if (iter == maps[command[1]].end() || command[2] < iter->first) {
  maps[command[1]].insert(iter, std::make_pair(command[2], command[3]));
} else {
  iter->second = command[3];
}

我收到以下编译时错误: no member named 'lower_bound' in 'std::unordered_map<std::basic_string<char>, std::basic_string<char>, std::hash<std::string>, std::equal_to<std::basic_string<char> >, std::allocator<std::pair<const std::basic_string<char>, std::basic_string<char> > > >'

1 个答案:

答案 0 :(得分:1)

顾名思义,unordered_map没有以任何特定的方式排序。因为lower_bound方法和函数引用元素的顺序,所以它们仅在有序数据上才有意义。这就是为什么unordered_map没有这种方法的原因。

许多编译器上的基准测试表明,std::map少于一千个元素,它的运行速度明显快于std::unordered_map。这意味着您应该考虑切换到std::map,或使用以下命令:

maps[command[1]].insert_or_assign(command[2], command[3]);