gpt4 book ai didi

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

转载 作者:可可西里 更新时间:2023-11-01 16:37:26 26 4
gpt4 key购买 nike

我有一个 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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com