1.map定义:
map 是一种有序无重复的关联容器。
Map是STL的一个关联容器,它提供一对一(其中第一个可以称为关键字,每个关键字只能在map中出现一次,第二个可能称为该关键字的值)的数据 处理能力,由于这个特性,它完成有可能在我们处理一对一数据的时候,在编程上提供快速通道。
2、map的功能
自动建立Key - value的对应。key 和 value可以是任意你需要的类型。
3.举例
自己错误的亲身经历
map<string,int> mp;
string ss;
for(int i=0;i<n;i++){
cin>>ss;
mp[ss]=i; //这里我开始加了引号,调了半天的错误!
}
//插入数据
mp["a"]=1;
mp.insert(map<string,int>::value_type("b",2));
//查找数据
int tmp=mp["a"];
map::iterator ite;
ite.find("a");
ite->second=j; //注意键的值不能修改,除非删除
#include<bits/stdc++.h>
using namespace std;
int main(){
map<int,string> mpstudent;
mpstudent[1]="student1";
mpstudent[2]="student2";
mpstudent[3]="student3";
//迭代器
map<int,string>::iterator ite;
for(ite=mpstudent.begin();ite!=mpstudent.end();++ite)
cout<<ite->first<<" "<<ite->second<<endl;
return 0;
}
注意:
STL中默认是采用小于号来排序的,当关键字是一个结构体时,涉及到排序就会出现问题。
因为它没有小于号操作,insert等函数在编译的时候过不去
#include <map>
#include <cstring>
using namespace std;
typedef struct tagStudentInfo
{
int nID;
string strName;
bool operator < (tagStudentInfo const & _A)const
{
// 这个函数指定排序策略,按nID排序,如果nID相等的话,按strName排序。
if (nID < _A.nID)
return true;
if (nID == _A.nID)
return strName.compare(_A.strName) < 0;
return false;
}
} StudentInfo, *PStudentInfo; // 学生信息
void main()
{
// 用学生信息映射分数
map<StudentInfo, int> mapStudent;
StudentInfo studentInfo;
studentInfo.nID = 1;
studentInfo.strName = "student_one";
mapStudent.insert(pair<StudentInfo, int>(studentInfo, 90));
studentInfo.nID = 2;
studentInfo.strName = "student_two";
mapStudent.insert(pair<StudentInfo, int>(studentInfo, 80));
}