map是STL的一个关联容器,他提供一一对应的数据处理能力(第一个为关键字,第二个为对应的值),并且能保证容器中的数据有序
用法(用一个班级中学生的学号和姓名进行举例)
1 创建
map<int, string> mapStudent;
2 清空
mapStudent.clear();
3 插入数据
3.1 直接插入
3.1.1 用pair<>()
mapStudent.insert(map<int, string>::value_type(5, shuying))
3.2 插入并判断是否成功
pair<map<int, string>, bool> pairResult;
pairResult = mapStudent.insert(pair<int, string>(23, "huan"));
if(!pairResult)
{
cout << "Opps, failed to insert element" << endl;
}
4 遍历数据
4.1 正序
map<int, string>::iterator itr;
for(itr = mapStudent.begin(); itr != mapStudent.end(); itr++)
{
cout << itr->first << " " << itr.second << endl;
}
4.2 逆序
map<int, string>::iterator itr;
for(itr = mapStudent.rbegin(); itr != mapStudent.rend(); itr++)
{
cout << itr->first << " " << itr.second << endl;
}
5 查找
itr = mapStudent.find(23);
if(itr != mapStudent.end())
{
cout << itr.first << " " << itr.second << endl;
}
6 大小
int nSize = mapStudent.size();
7 删除
mapStudent.erase(itr);
用法(用一个班级中学生的学号和姓名进行举例)
1 创建
map<int, string> mapStudent;
2 清空
mapStudent.clear();
3 插入数据
3.1 直接插入
3.1.1 用pair<>()
mapStudent.insert(pair<int, string>(16, "qiao"));
mapStudent.insert(map<int, string>::value_type(5, shuying))
3.2 插入并判断是否成功
pair<map<int, string>, bool> pairResult;
pairResult = mapStudent.insert(pair<int, string>(23, "huan"));
if(!pairResult)
{
cout << "Opps, failed to insert element" << endl;
}
4 遍历数据
4.1 正序
map<int, string>::iterator itr;
for(itr = mapStudent.begin(); itr != mapStudent.end(); itr++)
{
cout << itr->first << " " << itr.second << endl;
}
4.2 逆序
map<int, string>::iterator itr;
for(itr = mapStudent.rbegin(); itr != mapStudent.rend(); itr++)
{
cout << itr->first << " " << itr.second << endl;
}
5 查找
itr = mapStudent.find(23);
if(itr != mapStudent.end())
{
cout << itr.first << " " << itr.second << endl;
}
6 大小
int nSize = mapStudent.size();
7 删除
mapStudent.erase(itr);
本文深入解析了C++ STL中的map容器,包括创建、清空、插入数据(直接插入与插入并判断)、遍历数据(正序与逆序)、查找元素、获取大小、删除元素等核心功能,通过实例讲解了如何高效地管理和操作键值对数据。
5308

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



