【问题标题】:Insert or update key in nested unordered map在嵌套无序映射中插入或更新键
【发布时间】:2019-03-29 15:58:18
【问题描述】:

我正在尝试更新嵌套映射中的键(如果存在)或插入它(如果不存在)。我正在尝试使用带有 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&lt;std::basic_string&lt;char&gt;, std::basic_string&lt;char&gt;, std::hash&lt;std::string&gt;, std::equal_to&lt;std::basic_string&lt;char&gt; &gt;, std::allocator&lt;std::pair&lt;const std::basic_string&lt;char&gt;, std::basic_string&lt;char&gt; &gt; &gt; &gt;'

【问题讨论】:

  • 那是因为std::unordered_map::lower_bound 不存在!在元素未排序的容器上寻找下限是没有意义的。
  • 那么有没有有效的方法来解决这个问题?
  • 使用find查看元素是否存在有什么问题?
  • 插入提示在基于散列的容器上并不是真正有用(除非新元素散列到与提示指向的元素相同,这基本上意味着它是同一个元素,在在这种情况下你无论如何都不会插入)。

标签: c++ nested unordered-map


【解决方案1】:

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

许多编译器上的许多基准测试表明,具有少于一千个元素的std::mapstd::unordered_map 快得多。这意味着您应该考虑切换到std::map,或使用以下内容:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-12-31
    • 2017-05-27
    • 1970-01-01
    • 2020-09-24
    • 2017-05-25
    • 1970-01-01
    • 2016-12-25
    • 1970-01-01
    相关资源
    最近更新 更多