STL--map常用函数
- 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
- 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
- 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。
STL--map常⽤函数// testSTLMap.cpp : 测试STL map常⽤⽅法
//
#include "stdafx.h"
#include <string>
#include <map>
#include <iostream>
using namespace std;
int _tmain(int argc, _TCHAR* argv[])
{
map<int,string> mapStu;
//使⽤pair插⼊数据
mapStu.insert(pair<int,string>(1,"luo"));
mapStu.insert(pair<int,string>(2,"xiong"));
//使⽤map的value_type插⼊函数
mapStu.insert(map<int,string>::value_type(3,"doudou"));
//使⽤pair来判断插⼊是否成功
pair<map<int,string>::iterator,bool> result;
result = mapStu.insert(map<int,string>::value_type(4,"jinxiong"));
if (result.second == false)
{
cout<<"false"<<endl;
}else{
cout<<"true"<<endl;
}
mapStu[4]="bao";
//find函数返回查询key所在的迭代器
map<int,string>::iterator iterFind = mapStu.find(1);
mapStu.erase(iterFind);
//适⽤迭代器遍历map
for(map<int,string>::iterator iter = mapStu.begin();iter!=mapStu.end();iter++)
{
cout<<"first:"<<iter->first<<" second:"<<iter->second<<endl;
}
//map包含数据的⼤⼩
cout<<"size of the map:"<<mapStu.size()<<endl;
//map中某个key出现的次数,只返回0或者1
cout<<"count of the 2:"<<mapStu.count(5)<<endl;
//清空map
mapStu.clear();
//判断map是否为空
if (mapStu.empty())
{
cout<<"map is empty!"<<endl;
}
else{
cout<<"map is not empty!"<<endl;
}
typedef struct studentInfo{
int s_id_;
string strName;
//必须重载
bool operator<(const studentInfo& stu)const{
if (stu.s_id_>s_id_)
{
return true;
}
else return false;
}
}stuInfo,*p_stuInfo;
stuInfo student;
student.s_id_ = 3;
student.strName = "luo";
//stuInfo必须重载⼩于号操作符,否则报错
map<stuInfo,int> mapScore;
mapScore.insert(pair<stuInfo,int>(student,80));
student.s_id_ = 2;
student.strName = "xiong";
mapScore.insert(map<stuInfo,int>::value_type(student,90));
typedef struct studentInfo2{
int s_id_;
string strName;
}stuInfo2,*p_stuInfo2;
//必须实现仿函数
class sortA{
public:
bool operator()(const stuInfo2& stu1,const stuInfo2& stu2)const{
if (stu1.s_id_<stu2.s_id_)
{
return true;
}
else return false;
}
};
stuInfo2 student2;
student2.s_id_ = 3;
student2.strName = "luo";
//必须加⼊仿函数sortA,否则报错
map<stuInfo2,int,sortA> mapScore2;
mapScore2.insert(pair<stuInfo2,int>(student2,80));
student2.s_id_ = 2;
student2.strName = "xiong";
mapScore2.insert(map<stuInfo2,int>::value_type(student2,90)); return0;
}。