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

