C++ STL 中的 map insert()
在本文中,我们将讨论 C++ STL 中 map::insert() 函数的工作原理、语法和示例。
什么是 C++ STL 中的 Map?
Map 是关联容器,它可以方便地存储由键值对组成的元素,并按特定顺序排列。在 map 容器中,数据始终通过其关联的键进行内部排序。map 容器中的值通过其唯一的键进行访问。
什么是 map::insert()?
map::insert() 函数是 C++ STL 中的内置函数,定义在……
由于 map 容器中的键是唯一的,插入操作会检查每个要插入的元素的键是否已存在于容器中,如果已存在,则不会插入该元素。
此外,map 容器通过其各自的键按升序维护所有元素。因此,每当我们插入一个元素时,它都会根据其键进入其相应的位置。
语法
1. Map_name.insert({key& k, value_type& val});
or
2. Map_name.insert(iterator& it, {key& k, value_type& val});
or
3. Map_name.insert(iterator& position1, iterator& position2);参数
此函数接受以下参数:
k − 这是与元素关联的键。该函数检查键是否已存在于容器中,如果已存在,则不会插入元素。
val − 要插入的值。
it − 值的迭代器类型,用于指定要插入元素的位置。
position1, position2 − position1 是起始位置,position2 是结束位置。当我们想要插入一系列元素时,可以使用我们要插入的多个元素的范围。
返回值
此函数返回指向 map 容器中新插入元素的迭代器。
示例
输入
map<char, int> newmap;
newmap[‘a’] = 1;
newmap[‘b’] = 2;
newmap[‘c’] = 3;
newmap.insert({d, 50});输出
a:1 b:2 c:3 d:50
示例
#include <bits/stdc++.h>
using namespace std;
int main() {
map<int, int> TP_Map;
TP_Map.insert({3, 50});
TP_Map.insert({2, 30});
TP_Map.insert({1, 10});
TP_Map.insert({4, 70});
cout<<"TP Map is : \n";
cout << "MAP_KEY\tMAP_ELEMENT\n";
for (auto i = TP_Map.begin(); i!= TP_Map.end(); i++) {
cout << i->first << "\t" << i->second << endl;
}
return 0;
}输出
TP Map is: MAP_KEY MAP_ELEMENT 1 10 2 30 3 50 4 70
示例
#include <bits/stdc++.h>
using namespace std;
int main() {
map<int, int> TP_Map;
TP_Map.insert({3, 50});
TP_Map.insert({2, 30});
TP_Map.insert({1, 10});
TP_Map.insert({4, 70});
auto i = TP_Map.find(4);
TP_Map.insert(i, { 5, 80 });
cout<<"TP Map is : \n";
cout << "MAP_KEY\tMAP_ELEMENT\n";
for (auto i = TP_Map.begin(); i!= TP_Map.end(); i++) {
cout << i->first << "\t" << i->second << endl;
}
return 0;
}输出
TP Map is: MAP_KEY MAP_ELEMENT 1 10 2 30 3 50 4 70 5 80
广告
数据结构
网络
关系数据库管理系统 (RDBMS)
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP