遍历

map也有迭代器

1
2
3
4
map<char, int> ::iterator it;
for (map<char, int> ::iterator it = ma.begin(); it != ma.end(); it ++){
cout << it->first << ' ' << it -> second << "\n";
}

排序

默认的map是按照key值从小到大排序。可以加个参数让其从大到小排序:

1
map <string, int, greater<string> > ma;

按照value排序, 利用了map和pair对应的关系,在加上vector的sort排序。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
typedef unsigned long long ull;
const int INF = 0x3f3f3f3f;
const int N = 1e5 + 5;
typedef pair<string, int> P;
bool cmp(const P &p1, const P &p2){
return p1.second > p2.second;
} // 设置优先级
map<string, int> ma;
map<string, int> ::iterator it;
vector<P> ve;
int main() {
for (it = ma.begin(); it != ma.end(); it++){
ve.push_back(P(it->first, it->second));
}
sort(ve.begin(), ve.end(), cmp);

return 0;
}