C ++ map insert()函数用于在map中插入新元素。
因为元素键在map中是唯一的,所以插入操作首先检查给定键是否已存在于map中,如果键已存在于map中,则它不会插入map中,并且迭代器将迭代到现有键返回,否则在map中插入新元素。
single element (1) pair<iterator,bool> insert (const value_type& val); // 在 C++ 11 之前 with hint (2) iterator insert (iterator position, const value_type& val); // 在 C++ 11 之前 range (3) template <class InputIterator> void insert (InputIterator first, InputIterator last); // 在 C++ 11 之前 single element (1) pair<iterator,bool> insert (const value_type& val); template <class P> pair<iterator,bool> insert (P&& val); //从 C++ 11 开始 with hint (2) iterator insert (const_iterator position, const value_type& val); template <class P> iterator insert (const_iterator position, P&& val); range (3) template <class InputIterator> void insert (InputIterator first, InputIterator last); //从 C++ 11 开始 initializer list (4) void insert (initializer_list<value_type> il); //从 C++ 11 开始
val:要插入map的键值。
position:提示要插入元素的位置。
first:要插入范围的起点。
last:要插入范围的末尾。
il:初始化列表。
它返回一个布尔对来指示是否发生插入,并返回一个指向新插入元素的迭代器。
让我们看一个将元素插入map的简单示例。
#include <iostream>
#include <map>
using namespace std;
int main() {
map<char, int> m = {
{'a', 1},
{'b', 2},
{'c', 3},
};
//插入新元素
m.insert(pair<char, int>('d', 4));
m.insert(pair<char, int>('e', 5));
cout << "Map包含以下元素" << endl;
for (auto it = m.begin(); it != m.end(); ++it)
cout << it->first << " = " << it->second << endl;
return 0;
}输出:
Map包含以下元素 a = 1 b = 2 c = 3 d = 4 e = 5
在上面的示例中,它只是插入具有给定键值对的元素。
让我们看一个简单的示例,将元素插入指定位置:
#include <iostream>
#include <map>
using namespace std;
int main(void) {
map<char, int> m = {
{'b', 2},
{'c', 3},
{'d', 4},
};
//以给定的位置插入元素
m.insert(m.begin(), pair<char, int>('a', 1));
m.insert(m.end(), pair<char, int>('e', 5));
cout << "Map包含以下元素" << endl;
for (auto it = m.begin(); it != m.end(); ++it)
cout << it->first << " = " << it->second << endl;
return 0;
}输出:
Map包含以下元素 a = 1 b = 2 c = 3 d = 4 e = 5
在上面的示例中,将元素插入到定义的位置,即在开始元素{'a',1}中插入元素,在结束元素{'e',5}中插入元素。
让我们看一个简单的示例,将一个map的元素插入另一个map。
#include <iostream>
#include <map>
using namespace std;
int main() {
map<char, int> m1 = {
{'a', 1},
{'b', 2},
{'c', 3},
{'d', 4},
{'e', 5},
};
map<char, int> m2; // 创建新的map容器 m2
m2.insert(m1.begin(), m1.end()); //从头到尾插入m1到m2的元素
cout << "Map包含以下元素" << endl;
for (auto it = m2.begin(); it != m2.end(); ++it){
cout << it->first << " = " << it->second << endl;
}
return 0;
}输出:
Map包含以下元素 a = 1 b = 2 c = 3 d = 4 e = 5
在上面的示例中,map容器m1具有五个元素,而map容器m2为空。insert()函数用于从m1的开头到m1的结尾插入m1到m2的元素,并显示m2容器的内容。
让我们看一个插入元素的简单示例。
#include <iostream>
#include <map>
using namespace std;
int main(void) {
map<int , string> m = {
{1, "Java"},
{2, "C++"},
{3, "SQL"},
};
m.insert({{4,"VB"}, {5, "Oracle"}});
cout << "Map 包含以下元素" << endl;
for (auto it = m.begin(); it != m.end(); ++it){
cout << it->first << " : " << it->second << endl;
}
return 0;
}输出:
Map包含以下元素 1 : Java 2 : C++ 3 : SQL 4 : VB 5 : Oracle
在上面的示例中,使用了另一种形式的insert()函数将元素插入到map中。