题目要求:
统计每个单词在输入中出现的次数
解决办法:
用标准库中的map来存储单词以及出现的次数。
这里会出现两种方法:
方法一、下标法
#include "pch.h"
#include <iostream>
#include<map>
#include<set>
#include<string>
using namespace std;
int main()
{
map<string, size_t> word_cout; //定义一个map类型,key为string类型,vlue为size_t类型
string word;
while (cin >> word) {
++word_cout[word]; //这一句非常关键,这里用了下标,当有word这个关键字的时候,value加1,如果没有的化,创建一个
} //key为word,赋初值vlue为0,然后++
for (const auto& a : word_cout) {
cout << a.first << " " << a.second << endl;
}
}
/*总结:这里呢,对map对象进行下标时,根据key的值来返回vlue,如果没有的话,就会创建一个节点
*/
方法二:insert插入法
#include "pch.h"
#include <iostream>
#include<map>
#include<string>
using namespace std;
int main()
{
map<string, size_t> a;
string word;
while (cin >> word) {
pair<map<string, size_t>::iterator, bool> b=a.insert({word,1});
if (!b.second)
++b.first->second; //这里这句也是关键哦
}
for (auto b = a.begin(); b != a.end(); ++b) {
cout << b->first << " " << b->second << endl;
}
}
//完美了,太棒啦!!!
这两种方式中都有特别精妙的地方所在。下标法中++word_cout[word]算是非常的精妙了。
分析:
1.如果word_cout中没有key为word的元素pair,就会创建一个,并且value初值为0,然后++,就会变成1.
2.如果wod_cout中有key为word的元素pair,不会添加,而word_cout[word],就是key为word对用的value,然后对value++。
第二种方式相对来说更好理解。
通过map容器中的成员函数insert来进行插入。如果已经有key为word的元素,不会插入新的值。insert函数返回一个pair对象,first成员变量是一个迭代器,second成员是一个bool类型变量,如果word_cout中已经存在key为word的元素,则返回中bool值为false.如果插入了新的元素,则bool为true.
程序中如果插入了新的元素,直接将他value赋值为1.。代表新插入的元素出现了一次。
如果已经存在了,则会进入if条件中,将对应的value++。