Namespaces
Variants

std::unordered_map<Key,T,Hash,KeyEqual,Allocator>:: emplace_hint

From cppreference.net

template < class ... Args >
iterator emplace_hint ( const_iterator hint, Args && ... args ) ;
(自 C++11 起)
(自 C++26 起为 constexpr)

向容器中插入一个新元素,使用 hint 作为插入位置的参考建议。

value_type 的构造函数(即 std:: pair < const Key, T > )会以与传递给函数时完全相同的参数调用,这些参数通过 std:: forward < Args > ( args ) ... 进行完美转发。

如果在操作后新元素数量大于旧的 max_load_factor() * bucket_count() 将发生重新哈希。
如果发生重新哈希(由于插入操作),所有迭代器将失效。否则(未发生重新哈希),迭代器不会失效。

目录

参数

hint - 迭代器,作为插入新元素位置的参考提示
args - 要转发给元素构造函数的参数

返回值

指向被插入元素的迭代器,或指向阻止插入的元素的迭代器。

异常

若因任何原因抛出异常,此函数不产生任何效果( 强异常安全保证 )。

复杂度

平均情况下摊销常数复杂度,最坏情况与容器大小呈线性关系。

示例

#include <chrono>
#include <cstddef>
#include <functional>
#include <iomanip>
#include <iostream>
#include <unordered_map>
const int n_operations = 100'500'0;
std::size_t map_emplace()
{
    std::unordered_map<int, char> map;
    for (int i = 0; i < n_operations; ++i)
        map.emplace(i, 'a');
    return map.size();
}
std::size_t map_emplace_hint()
{
    std::unordered_map<int, char> map;
    auto it = map.begin();
    for (int i = 0; i < n_operations; ++i)
    {
        map.emplace_hint(it, i, 'b');
        it = map.end();
    }
    return map.size();
}
std::size_t map_emplace_hint_wrong()
{
    std::unordered_map<int, char> map;
    auto it = map.begin();
    for (int i = n_operations; i > 0; --i)
    {
        map.emplace_hint(it, i, 'c');
        it = map.end();
    }
    return map.size();
}
std::size_t map_emplace_hint_corrected()
{
    std::unordered_map<int, char> map;
    auto it = map.begin();
    for (int i = n_operations; i > 0; --i)
    {
        map.emplace_hint(it, i, 'd');
        it = map.begin();
    }
    return map.size();
}
std::size_t map_emplace_hint_closest()
{
    std::unordered_map<int, char> map;
    auto it = map.begin();
    for (int i = 0; i < n_operations; ++i)
        it = map.emplace_hint(it, i, 'e');
    return map.size();
}
double time_it(std::function<std::size_t()> map_test,
               std::string what = "", double ratio = 0.0)
{
    const auto start = std::chrono::system_clock::now();
    const std::size_t map_size = map_test();
    const auto stop = std::chrono::system_clock::now();
    std::chrono::duration<double, std::milli> time = stop - start;
    if (what.size() && map_size)
        std::cout << std::setw(8) << time << " for " << what << " (ratio: "
                  << (ratio == 0.0 ? 1.0 : ratio / time.count()) << ")\n";
    return time.count();
}
int main()
{
    std::cout << std::fixed <span

参见

td> 插入元素 或节点 (C++17 起)
(公开成员函数)
原地构造元素
(公开成员函数)