map(STL)

性质

Each element(元素) has a key value and a mapped value. No two mapped values can(可以) have the same key values.借用网站上的话解释的非常清晰。

一些常用的函数

1
2
3
4
5
6
7
8
9
10
11
//创建map
map<string,int> mp
//begin函数,返回第一个元素的迭代器,要专门写一个迭代器去接受
std::map<std::string, int>::iterator it = map.begin();
mp.begin()
//end()
mp.end()//返回最后一个迭代器
//find()
mp.find(key)//找到S的对应的迭代器
//count(key)
mp.count(key)//找到对应的value的个数0或者1

一道练习题

空中有n个气球,第i个气球有一个颜色coli​(用一个字符串表示)。

请你求出每种气球的个数,按照气球出现的顺序进行排序输出。

输入格式

第一行一个整数T表示样例个数。(1≤T≤10)

对于每个样例,第一行一个整数n表示气球个数。(1≤n le100)

接下来n行,每行一个字符串表示coli​。(1≤∣coli​∣≤50)

字符串仅包含小写英文字母。

1
2
3
4
5
6
7
8
9
10
11
12
13
样例输入 
2
3
red
red
blue
5
a
b
e
d
e

1
2
3
4
5
6
7
red 2
blue 1
a 1
b 1
e 2
d 1
### 样例输出

输出格式

对于每个样例,输出所有气球的种类和个数。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
#include <bits/stdc++.h>

using namespace std;

typedef long long ll;

constexpr int N = 1e5 + 10;

void solve() {

map<string, int> mp;

vector<string> v;

int n;

cin >> n;

for (int i = 1; i <= n; i++) {

string s;

cin >> s;

if (mp.find(s) != mp.end())

mp[s]++;

else

v.push_back(s), mp[s] = 1;

}

for (auto &i : v) cout << i << ' ' << mp[i] << '\n';

}

int main() {

ios::sync_with_stdio(0);

cin.tie(0);

cout.tie(0);

int m;

cin >> m;

while (m--) {

solve();

}

return 0;

}

关于map遍历顺序的问题

当你为MAP插入一个元素后,MAP会按KEY的顺序重新排列,所以当你遍历MAP的时候,遍历的顺序已经不是你插入元素的顺序。举个具体例子:

MAP【‘B’】=1
MAP【‘C’】=2
MAP【’A‘】=3
当你遍历MAP输出的时候,是按’A’,’B’,’C’顺序输出的,而不是’B’,’C’,’A’顺序输出。如果你要遍历的顺序就是插入元素的顺序,你必须用线性容器,比如VECTOR

map(STL)
https://ljw030710.github.io/2023/10/28/map-STL/
Author
iolzyy
Posted on
October 28, 2023
Licensed under