1.map基本用法
#include<iostream>
#include<set>
#include<map>
using namespace std;
class MyCompare{
public:
bool operator()(string v1,string v2)const{
return v1>v2;
}
};
void PrintMap(map<string,int,MyCompare> &m){
for(map<string,int>::iterator it=m.begin();it!=m.end();it++){
cout<<"key:"<<it->first<<" value:"<<it->second<<endl;
}
}
int main(){
map<string,int,MyCompare>m;
//插入
//m.insert(make_pair("yzq",18));
m.insert(pair<string,int>("yzq",18));
m.insert(make_pair("sxy",19));
m.insert(make_pair("dwj",20));
//删除 --按照key和迭代器
//m.erase("dwj");
m.erase(m.begin());
PrintMap(m);
//查找和统计
map<string,int,MyCompare>::iterator p = m.find("yzq");
if(p!=m.end()){
cout<<"找到了:"<<p->first<<endl;
}else{
cout<<"找不到"<<endl;
}
return 0;
}
2.自定义容器 实现名字降序 年龄升序
map是按照key升序排列的,且key不能有重复
multimap的key可以重复
map可以实现key降序排列,但是不能实现对value升/降序,可借用multiset等
#include <iostream>
#include <map>
#include <string>
#include<set>
using namespace std;
class MyCompare {
public:
bool operator()(const pair<string, int>& p1, const pair<string, int>& p2) const {
if (p1.first != p2.first) {
return p1.first > p2.first;
} else {
return p1.second < p2.second;
}
}
};
void PrintSet(multiset<pair<string, int>,MyCompare>s) {
for (multiset<pair<string, int>,MyCompare>::iterator it = s.begin(); it != s.end(); ++it) {
cout << "key: " << it->first << " value: " << it->second << endl;
}
}
int main() {
multiset<pair<string, int>, MyCompare> s;
s.insert(make_pair("yzq", 18));
s.insert(make_pair("yzq", 3));
s.insert(pair<string, int>("yxc", 20));
PrintSet(s);
return 0;
}