C++ Map 库 - insert() 函数
描述
C++ 函数 std::map::insert() 通过插入新元素来扩展映射。 此函数将容器大小增加一。
声明
以下是 std::map::insert() 函数形式 std::map 头的声明。
C++11
template <class P> iterator insert (const_iterator position, P&& val);
参数
position − 提示插入元素的位置。
val − 要插入的值。
返回值
返回一个指向新插入元素的迭代器。
异常
该成员函数不会抛出异常。
时间复杂度
Logarithmic i.e. O(log n).
示例
以下示例显示了 std::map::insert() 函数的用法。
#include <iostream>
#include <map>
using namespace std;
int main(void) {
map<char, int> m = {
{'b', 2},
{'c', 3},
{'d', 4},
};
m.insert(m.begin(), move(pair<char, int>('a', 1)));
m.insert(m.end(), move(pair<char, int>('e', 5)));
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

