Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/cplusplus/155.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ 我可以依赖无序地图的顺序吗?_C++_C++11_Gcc_Language Lawyer_Multimap - Fatal编程技术网

C++ 我可以依赖无序地图的顺序吗?

C++ 我可以依赖无序地图的顺序吗?,c++,c++11,gcc,language-lawyer,multimap,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", "fir

我有一个
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;
}
至少在GCC上,这是我想要的行为。我能相信这个吗?该标准是否规定了
std::unordered\u multimap
存储物品的顺序?如果没有,那么最好的选择是什么?

差不多

[C++14:24.2.5/6]:
[…]在支持等价键的容器中,具有等价键的元素按照容器的迭代顺序彼此相邻。因此,尽管未指定无序容器中元素的绝对顺序,但其元素被分组为等价的键组,以便每组的所有元素都具有等价的键除非另有规定,否则无序容器上的变异操作应保持每个等效密钥组中元素的相对顺序。

[C++14:24.2.5/9]:
[…]对于无序的多集和无序的多映射,重灰化保留了等效元素的相对顺序。

这是一个相当尴尬的措辞,但据我所知,一般的概念是,等价键下的元素顺序是未指定的,尽管之后它至少基本保持不变

因此:

你不能依赖插入顺序,但如果你小心的话,你可以依赖稳定的顺序。

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

[C++14:23.2.4/4]:
对于多集和多映射,插入、放置和擦除保留等效元素的相对顺序。


std::unordered_multimap
既不有序(显然),也不稳定。因此,标准无法保证将等效元素放入std::unordered_multimap中的顺序是一致的。

但没有指定新元素插入的位置。如果在等效密钥组中有
a、b、c
,并插入
d
,则
a
b
c
的相对顺序不会改变,但您可以在这四个位置中的任何一个插入
d
。@T.C.这可能是确定的,也可能不是确定的。该措辞表明了很强的稳定性。@LightnessRacesinOrbit等效元素仅保证在迭代顺序的连续子范围内。@P​​​​​​​​​​​​aulEvans我知道。您将获得
第一个1
last
3