//唯一性检查或重复就覆盖(新值替旧值)
#include <map>
#include <string>
#include <iostream>
using namespace std;
void DispMap(map<int, string>& mpStu)
{
cout << "Begin****************************************************" << endl;
for(map<int, string>::iterator it = mpStu.begin(); it != mpStu.end(); it ++){
cout << it->first << " : " << it->second << endl;
}
cout << "End****************************************************" << endl << endl;
}
//用insert函数插入pair数据
void MapTst1()
{
//进行主键唯一性检查:如果存在,插入失败
map<int, string> mapStudent;
mapStudent.insert(pair<int, string>(1, "student_one"));
mapStudent.insert(pair<int, string>(1, "student_two"));
mapStudent.insert(pair<int, string>(3, "student_three"));
DispMap(mapStudent);
}
//用insert函数插入value_type数据
void MapTst2()
{
//进行主键唯一性检查:如果存在,插入失败
map<int, string> mapStudent;
mapStudent.insert(map<int, string>::value_type (1, "student_one"));
mapStudent.insert(map<int, string>::value_type (1, "student_two"));
mapStudent.insert(map<int, string>::value_type (3, "student_three"));
DispMap(mapStudent);
}
//用数组方式插入数据
void MapTst3()
{
//不进行主键唯一性检查:如果存在,覆盖之前的键值
map<int, string> mapStudent;
mapStudent[1] = "student_one";
mapStudent[1] = "student_two";
mapStudent[3] = "student_three";
DispMap(mapStudent);
}
void main()
{
cout << "Way1 : 用insert函数插入pair数据" << endl;
MapTst1();
cout << "Way2 : 用insert函数插入value_type数据" << endl;
MapTst2();
cout << "Way3 : 用数组方式插入数据" << endl;
MapTst3();
}
本文通过三种不同方式展示了如何使用 C++ 中的 map 容器进行数据插入操作,并对比了不同插入方法的特点。包括使用 insert 函数插入 pair 和 value_type 数据,以及采用数组方式直接赋值。
2万+

被折叠的 条评论
为什么被折叠?



