持续创作,加速成长!这是我参与「掘金日新计划 · 10 月更文挑战」的第14天,点击查看活动详情
1.1 map插入和删除
功能描述:
- map容器进行插入数据和删除数据
1.2 函数原型:
insert(elem);//在容器中插入元素。clear();//清除所有元素erase(pos);//删除pos迭代器所指的元素,返回下一个元素的迭代器。erase(beg, end);//删除区间[beg,end)的所有元素 ,返回下一个元素的迭代器。erase(key);//删除容器中值为key的元素。
1.3 代码示例:
#include <map>
void printMap(map<int,int>&m)
{
for (map<int, int>::iterator it = m.begin(); it != m.end(); it++)
{
cout << "key = " << it->first << " value = " << it->second << endl;
}
cout << endl;
}
void test01()
{
//插入
map<int, int> m;
//第一种插入方式
m.insert(pair<int, int>(1, 10));
//第二种插入方式
m.insert(make_pair(2, 20));
//第三种插入方式
m.insert(map<int, int>::value_type(3, 30));
//第四种插入方式
m[4] = 40;
printMap(m);
//删除
m.erase(m.begin());
printMap(m);
m.erase(3);
printMap(m);
//清空
m.erase(m.begin(),m.end());
m.clear();
printMap(m);
}
int main() {
test01();
system("pause");
return 0;
}
1.4 总结:
- map插入方式很多,记住其一即可
- 插入 --- insert
- 删除 --- erase
- 清空 --- clear
1.5 在构造map容器后,我们就可以往里面插入数据了。这里讲四种插入数据的方法:
第一种:用insert函数插入pair数据:在VC下请加入这条语句,屏蔽4786警告 #pragma warning (disable:4786) ) map<int, string> mapStudent;
mapStudent.insert(pair<int, string>(1, "student_one"));
mapStudent.insert(pair<int, string>(2, "student_two"));
mapStudent.insert(pair<int, string>(3, "student_three"));
第二种:用insert函数插入value_type数据,下面举例说明 map<int, string> mapStudent;
mapStudent.insert(map<int, string>::value_type (1, "student_one"));
mapStudent.insert(map<int, string>::value_type (2, "student_two"));
mapStudent.insert(map<int, string>::value_type (3, "student_three"));
第三种:在insert函数中使用make_pair()函数,下面举例说明 map<int, string> mapStudent;
mapStudent.insert(make_pair(1, "student_one"));
mapStudent.insert(make_pair(2, "student_two"));
mapStudent.insert(make_pair(3, "student_three"));
第四种:用数组方式插入数据,下面举例说明 map<int, string> mapStudent;
mapStudent[1] = "student_one";
mapStudent[2] = "student_two";
mapStudent[3] = "student_three";