map简介
作为STL库中一个关联容器,它的两个关键字存在一对一的**映射关系**。内部实现自建红黑树,具有对数据**自动排序**的功能。
基本函数
#include<iostream>
#include<algorithm>
#include<cmath>
#include<map>//map的头文件别忘记
#define TIE ios::sync_with_stdio(false),cin.tie(0),cout.tie(0)//关闭输入输出流,加速cin、cout的
using namespace std;
map<string, int> m;
int main() {
TIE;
m["WA"] = 1;
m["TLE"] = 2;
m["AC"] = 3;
m.insert({"RE", 4}); //也可以这样插入,可是我个人比较喜欢上面的赋值操作
map<string, int>::iterator it, it1, it2, it3;
cout<<"遍历:";
for (it = m.begin(); it != m.end(); ++it) {
cout << it->first << ":" << it->second << " ";
}//这就是使用迭代器遍历,很容易看出,map是自动按照第一关键字进行排序的(从小到大)
cout << "\n";
it1 = m.find("AC");
cout << "查找:" << it1->first << "\n"; //如果找不到,it1的位置是m.end()
m.erase(it1);
cout<<"删除后:";
for (it = m.begin(); it != m.end(); ++it) {
cout << it->first << ":" << it->second << " ";
}
cout<<"\n";
if (m.count("AC")) {
cout << "AC is exist" << "\n";
} else cout << "-1"; //在map中自动去重,count函数要么返回值为1要么为0
m.clear();//如果题目中有多组输入,记得清空map,类似数组memset
return 0;
}
附上代码运行结果~~~
tip:像我这样的蒟蒻初学map要多动手实现,搜其他dalao的博客都是讲解函数源码和作用,所以还是自己多敲才能熟练~~
一个小破题
题目描述
仓库里面堆积着很多的货物。某蒟蒻放假归来,发现仓库里多了许多的货物。
某蒟蒻作为仓库管理员,需要对新多出来的货物进行分类整理。但是这段时间多出来的货物太多了,你能帮某蒟蒻整理一下吗?输入描述
第一行一个正整数T(1≤ T≤ 10),代表有T组数据。
对于每组数据,第一行有一个正整数n,代表有n条入库记录。
接下来有n行入库记录。
每个入库记录由字符串a,b和一个正整数m(1≤ m≤ 100)组成,a是货物名,b是货物来源,m是数量。这两个字符串的长度都不长于80输出描述
请输出合并整理后格式正确的货物统计表。格式为:
把货物按照来源地分类,来源地按照字典序排序输出。每个来源地都有下级分类。 每个来源地下级分类中,每一行输出三个空格,一个|,四个-,用来保持缩进。子分类中,将来源地是此来源地的货物按照字典序排序,每个货物后面有一个括号,里面写货物的总数量。具体格式参考样例
样例输入
1
5
pencil shandong 3
eraser guangdong 1
water sichuan 1
eraser guangdong 3
water guangdong 1
样例输出
guangdong
|----eraser(4)
|----water(1)
shandong
|----pencil(3)
sichuan
|----water(1)
这个题呢我用的是map嵌套map的做法,小模拟QWQ
#include<iostream>
#include<map>
#define TIE ios::sync_with_stdio(false),cin.tie(0),cout.tie(0)
using namespace std;
map<string,map<string,int> > ma;
int n,t;
int main(){
TIE;cin>>t;
while(t--){
ma.clear();
cin>>n;
while(n--){
string sub,ru;
int m;
cin>>sub>>ru>>m;
ma[ru][sub]+=m;
}
map<string,map<string,int> >::iterator it;
for(it=ma.begin();it!=ma.end();++it){
cout<<it->first<<"\n";
map<string,int>::iterator i;
for(i=(it->second).begin();i!=(it->second).end();++i){
cout<<" |----"<<i->first<<"("<<i->second<<")"<<"\n";
}
}
printf("\n");
}
return 0;
}
map的排序
#include <map>
#include <string>
#include <iostream>
using namespace std;
map<string, int, greater<string> >m; //第一关键字从大到小
int main() {
m["AC"] = 1;
m["RE"] = 2;
m["TLE"] = 3;
map<string, int>::iterator it;
for (it = m.begin(); it != m.end(); it++) {
cout << it->first << " " << it->second << endl;
}
return 0;
}
还可以用重定义,让你的排序玩出花
#include <map>
#include <string>
#include <iostream>
using namespace std;
struct node{
bool operator()(const string&s1,const string&s2){
if(s1.size()==s2.size()) return s1>s2;
return s1.size()>s2.size();
}
};
int main() {
map<string, int,node>m; //第一关键字从大到小
m["AC"] = 1;
m["RE"] = 2;
m["TLE"] = 3;
map<string, int>::iterator it;
for (it = m.begin(); it != m.end(); it++) {
cout << it->first << " " << it->second << endl;
}
return 0;
}
完结撒花~~