map的学习
最近在学c++,一直是在看视频,还是觉得不行,学得有点superficial,所以还是想记录一下。不写纸上了,也没有按顺序。
- map是建立一种映射关系,map<pair<y,x>>,一个y可以对应几个x,但是不能几个x对应一个y。
- 建立这种映射关系有三种方法,pair,value_type,数组法。
- pair语法
#include<bits/stdc++.h>
using namespace std;
int main()
{
map<int, string> ChampionClub;
ChampionClub.insert(pair<int,string>(1,"ARS"));
ChampionClub.insert(pair<int,string>(2,"LIV"));
ChampionClub.insert(pair<int,string>(3,"MUN"));
map<int, string>::iterator iter;
for(iter=ChampionClub.begin();iter!=ChampionClub.end();iter++)
cout<<iter->second<<" is "<<iter->first<<endl;
}
其中iter是定义在map类内的指向对象的指针
如果在以及对key值“1"建立映射为ARS后,再ChampionClub.insert(pair<int,string>(1,"LIV"));
就无效,若想再对1建立新的映射,可以先用erase(1)取消1的映射,再建立新的映射/
- value_type
#include <map>
#include <string>
#include <iostream>
using namespace std;
int main()
{
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"));
map<int, string>::iterator iter;
for(iter = mapStudent.begin(); iter != mapStudent.end(); iter++)
cout<<iter->first<<' '<<iter->second<<endl;
}
我自己还不是很懂,就直接copy了
- 数组法
#include<bits/stdc++.h>
using namespace std;
int main()
{
map<string,int> ChampionClub;
ChampionClub["ARS"]=1;
ChampionClub["LIV"]=2;
ChampionClub["TOT"]=3;
map<string,int>::iterator iter;
for(iter=ChampionClub.begin();iter!=ChampionClub.end();iter++)
cout<<iter->first<<" is "<<iter->second<<endl;
}
我觉得这个很直接,比较好理解。建立新的映射比较方便,如
#include<bits/stdc++.h>
using namespace std;
int main()
{
map<string,int> ChampionClub;
ChampionClub["ARS"]=1;
ChampionClub["LIV"]=2;
ChampionClub["LIV"]=3;
ChampionClub["TOT"]=3;
map<string,int>::iterator iter;
for(iter=ChampionClub.begin();iter!=ChampionClub.end();iter++)
cout<<iter->first<<" is "<<iter->second<<endl;
}
OUTPUT:
ARS is 1
LIV is 5
TOT is 3
这里就直接改变LIV的映射,整个映射关系中只有3种映射关系。
一些map的语句
-
begin()返回map头部迭代器
-
end()返回尾部迭代器
-
clear()清空所有元素
-
erase()删除一个元素
-
find()查找一个元素
-
empty()如果为空则返回true
-
size()返回map大小
-
count(elem)返回某个元素个数