STL之map

本文最后更新于:2023年8月26日 晚上

map的用法

和multimap的区别在于:

  • 不能有关键字重复的元素
  • 可以使用[],下标为关键字,返回值为first和关键字相同的元素的second
  • 插入元素可能失败

应用举例:单词词频统计程序

输入大量单词,每个单词,一行,不超过20个字符,没有空格。(验证发现可以直接输入,程序会以空格或换行来检测一个单词输入的结束)按出现次数从多到少输出这些单词及其出现次数。出现次数相同的,字典序靠前的在前面。

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
#include<iostream>
#include<set>
#include<map>
#include<string>
using namespace std;
struct Word {
int times;
string wd;
};
struct Rule {
bool operator () (const Word & w1, const Word & w2) const {
if( w1.times != w2.times)
{
return w1.times > w2.times;//优先按次数排序
}
else
return w1.wd < w2.wd;//次数相同,按名称字典序排序
}
};
int main()
{
string s;
set< Word, Rule > st;
map< string,int > mp;
while(cin >> s) {//ctrl+z结束循环
++mp[s];//如果s已存在mp中,则mp[s]返回值为次数,再进行++;如果还未存在,则创建该元素mp[s],再将返回值次数++
}
for( map<string,int>::iterator i = mp.begin(); i!= mp.end() ;i++){//将mp中的元素复制到st中,进行自动排序
Word temp;
temp.wd = i->first;
temp.times = i->second;
st.insert(temp);
}
for(set<Word,Rule>::iterator i =st.begin(); i != st.end(); i++){
cout<<i->wd << ' '<<i->times <<endl;
}
return 0;
}

STL之map
https://furthur509.github.io/2023/08/26/STL之map/
作者
Yang Mingxin
发布于
2023年8月26日
许可协议