c++ - std::multimap 上的 emplace_hint 是否保留等效元素的相对顺序?

标签 c++ multimap emplace

根据 http://www.cplusplus.com/reference/map/multimap/emplace_hint/

The relative ordering of equivalent elements is preserved, and newly inserted elements follow their equivalents already in the container.

The value in position is used as a hint on the insertion point. The element will nevertheless be inserted at its corresponding position following the order described by its internal comparison object, but this hint is used by the function to begin its search for the insertion point, speeding up the process considerably when the actual insertion point is either position or close to it.

据我了解,提示只是提示,根本不应该影响排序。 但似乎 clang++(11) 和 g++(10) 都不是这种情况,无论选项或 c++ 指定的标准如何。

 int main()
{
    std::multimap<int, string> mymap;
    // emplace
    mymap.emplace(0, "First");
    mymap.emplace(0, "Second");

    // emplace_hint
    mymap.emplace_hint(mymap.end(), 1, "First");
    // Insert with the previously inserted element as hint
    mymap.emplace_hint(--mymap.end(), 1, "Second");

    for (auto it = mymap.begin(); it != mymap.end(); ++it) {
        std::cout << it->first << " " << it->second << std::endl;
    }
    return 0;
}

输出

0 First
0 Second
1 Second
1 First

这是预期的行为吗?

最佳答案

该引用来自 cplusplus.com,似乎有误。来自 C++ 标准:

22.2.6 Associative containers [associative.reqmts]

...

An associative container supports unique keys if it may contain at most one element for each key. Otherwise, it supports equivalent keys. The set and map classes support unique keys; the multiset and multimap classes support equivalent keys. For multiset and multimap, insert, emplace, and erase preserve the relative ordering of equivalent elements.

请注意,仅列出了 emplace,但未列出 emplace_hint

C++11 标准和当前标准中都出现了相同的措辞,因此该措辞最近没有任何更改。

关于c++ - std::multimap 上的 emplace_hint 是否保留等效元素的相对顺序?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65445096/

相关文章:

Java Multimap 具有自然排序的键,但集合按添加元素的顺序排序

c++ - std::map::emplace 无法解析,但插入右值有效——为什么?

c++ - 我可以在 Rust 中就地构建吗?

c++ - 神秘的 C++ "thing"(函数指针)

c++ - Qt 应用程序在 Windows 10 上缺少开始菜单和任务栏图标

java - 如何在java中将csv转换为multiMap?

c++ - 交换 multimap<int, int> 中的每对值

c++ - ./a,输出: error while loading shared libraries and linking

c++ - 您的计算机中缺少 libgcc_s_sjlj-1.dll

c++ - 为什么 vector 构造函数在 unordered_map emplace 中使用时只采用参数的最后一个值?