C++ Unordered_map 库 - emplace_hint() 函数
描述
C++ 函数 std::unordered_map::emplace_hint() 在 unordered_map 中插入一个新元素,使用提示作为元素的位置。
声明
以下是 std::unordered_map::emplace_hint() 函数形式 std::unordered_map 头的声明。
C++11
template <class... Args> iterator emplace_hint(const_iterator position, Args&&... args);
参数
position − 提示插入元素的位置。
args − 转发参数以构造新元素。
返回值
返回指向新插入元素的迭代器。 如果插入由于已经存在的元素而失败,它会将迭代器返回到现有元素。
时间复杂度
常数,即平均情况下的 O(1)。
线性,即最坏情况下的 O(n)。
示例
以下示例显示了 std::unordered_map::emplace_hint() 函数的用法。
#include <iostream>
#include <unordered_map>
using namespace std;
int main(void) {
unordered_map<char, int> um = {
{'b', 2},
{'c', 3},
{'d', 4},
};
um.emplace_hint(um.end(), 'e', 5);
um.emplace_hint(um.begin(), 'a', 1);
cout << "Unordered map contains following elements" << endl;
for (auto it = um.cbegin(); it != um.cend(); ++it)
cout << it->first << " = " << it->second << endl;
return 0;
}
让我们编译并运行上面的程序,这将产生以下结果 −
Unordered map contains following elements a = 1 e = 5 d = 4 b = 2 c = 3

