c++ - 我可以依赖无序 map 的顺序吗?

标签 c++ c++11 gcc language-lawyer multimap

我有一个 std::unordered_multimap,我想获取特定键的最后插入的元素。我观察到这种行为:

#include <iostream>
#include <string>
#include <unordered_map>

using namespace std;

int main() {
    unordered_multimap<string, string> mmap;

    mmap.emplace("a", "first");
    mmap.emplace("a", "second");
    mmap.emplace("a", "last");
    mmap.emplace("b", "1");
    mmap.emplace("b", "2");
    mmap.emplace("b", "3");

    auto last_a = mmap.equal_range("a").first;
    auto last_b = mmap.equal_range("b").first;

    cout << last_a->second << endl;
    cout << last_b->second << endl;

    return 0;
}

这段代码输出:

last
3

至少,在 GCC 上,这是我想要的行为。我可以依靠这个吗?标准是否说明了 std::unordered_multimap 存储事物的顺序?如果不是,最好的选择是什么?

最佳答案

差不多。

[C++14: 24.2.5/6]: [..] In containers that support equivalent keys, elements with equivalent keys are adjacent to each other in the iteration order of the container. Thus, although the absolute order of elements in an unordered container is not specified, its elements are grouped into equivalent-key groups such that all elements of each group have equivalent keys. Mutating operations on unordered containers shall preserve the relative order of elements within each equivalent-key group unless otherwise specified.

[C++14: 24.2.5/9]: [..] For unordered_multiset and unordered_multimap, rehashing preserves the relative ordering of equivalent elements.

这是非常尴尬的措辞,但据我所知,一般概念是等效键下元素的顺序是未指定的,尽管它至少在之后几乎保持不变。

所以:

您不能依赖广告订单,但如果您小心的话,您可能可以依赖稳定的订单。

这与有序关联容器形成对比:

[C++14: 23.2.4/4]: For multiset and multimap, insert, emplace, and erase preserve the relative ordering of equivalent elements.

关于c++ - 我可以依赖无序 map 的顺序吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34582666/

相关文章:

c++ - Ubuntu 上的 Qt 5.1.1 编译器设置

c++ - 即使程序刚刚启动,是否也可以始终捕获信号?

c++ - 我需要一些指导来编写哈希函数来对 ~160,000 个字符串进行排序

c++ - UCI 种子数据集上的 CGAL::Delaunay_d C++: “EXC_BAD_ACCESS”

c++ - 我可以在这个类中用嵌套类填充模板参数吗?

multithreading - 为什么不在 fill_n 中调用移动构造函数

c++ - 在方法中返回静态变量是个坏主意吗?

c++ - 使用 std::function 作为类成员创建回调

c++ - 模板类中的 setter

eclipse - 使用适用于 Linux 的 Windows 子系统在 eclipse 上设置 Linux gcc 工具链/编译器