紙上談兵
1、說明:
- hash單值映射
- 常用於字符串轉數字
- 自動按主鍵值升序排序
- 聲明後默認尾部數據爲空
2、聲明:
map<主鍵頭部數據類型,尾部數據類型> 變量名
例:map<string , int> nametonum;
還可以是 map<string , struct student> stu //學號映射到學生信息
3、賦值:
例:nametonum[“jiangchulang”]=1
或stu[“1234567”]={“jiangchulang”,“111歲”,“男”};
4、容器大小:
stu.size();
5、清空:
stu.clear();
6、判空:
stu.empty();
7、查尋指定元素:
if(stu.find[“1234567”] !=stu.end())
cout<<stu[“1234567 ”].name<<endl;
//或者
if(nametonum[“jiangchulang”])
cout <<“查有此人”<<endl;//原因看說明 第四點
8、只能是迭代器實現遍歷:
- 正向遍歷:
for(auto it = stu.begin() , it !=stu.end() , ++it)
cout <<it->first<<“ ”<<it->second<<endl;
- 反向遍歷:
for(auto it = stu.rbegin() , it !=stu.rend() , ++it)
cout <<it->first<<“ ”<<it->second<<endl;
9、排序:
必須藉助vector輔助排序:
bool cmp (pair<string , struct student> a , pair<string , struct student> b)
{
return a.second.age>b.second.age;//按年齡排降序
}
vector<pair<string , struct student>> ans(stu.begin(),stu.end());
sort(ans.begin() , ans.end() , cmp);
10、刪除指定元素:
stu.erase(stu.find(“jiangchulang”));
11、因爲map會自動升排,所以會多出nlogn的時間複雜度,此時可以使用unordered_map替換掉map即可,其他用法與map一致
實戰演練
#include<iostream>
#include<unordered_map>
#include<vector>
#include<string>
#include<algorithm>
using namespace std;
struct student{
string name;
int age;
string gender;
};
bool cmp(pair<string,struct student> a,pair<string,struct student> b)
{
return a.second.age>b.second.age;
}
int main()
{
int n;
cin>>n;
unordered_map<string,struct student> stu;
for(int i=0;i<n;++i)
{
string name,gender,num;
int age;
cin>>num>>name>>age>>gender;
stu[num]={name,age,gender};
}
vector<pair<string,struct student>> ans(stu.begin(),stu.end());
sort(ans.begin(),ans.end(),cmp);
for(auto it = ans.begin();it!=ans.end() ;++it)
cout<<(*it).first<<" "<<(*it).second.name<<endl;
return 0;
}