map常见实用总结——没错,就是你要找的那种

纸上谈兵

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一致

实战演练 

PAT甲级例题

#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;
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章