根据 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/