map容器,下标行为的编程意义

本文介绍了一种利用C++中的map容器来统计输入文本中各单词出现频率的方法。通过键值对应的方式,能够高效地记录并更新每个单词的计数。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

关联容器与顺序容器的本质差别在于:一个是按键存储和访问元素,另一个是按元素在容器中的位置顺序存储和读取元素。

在map容器中,如果下标表示的键不存在则创建新元素,这一特性对于统计单词的频率非常简单!

#include<iostream>
#include<map>
#include<algorithm>
#include<vector>
#include<string>
using namespace std;

int main()
{
	map<string,int> word_count; //word_count用来记录单词出现的次数
	vector<string> words;

	cout<<"Enter some words:"<<endl;
	string word;
	while(cin>>word)
	{
		//如果该键不存在,则将它放入容其中
		if( find(words.begin(),words.end(),word)==words.end() )
				words.push_back(word);

		++word_count[word];
        }
	cout<<endl<<"The word are:"<<endl;
	for(vector<string>::iterator it=words.begin();it!=words.end();++it)
		cout<<*it<<": "<<word_count[*it]<<endl;

	return 0;
}

Enter some words:
hot tokyo bath angel lip lip hot bath

The word are:
hot: 2
tokyo: 1
bath: 2
angel: 1
lip: 2

转载于:https://my.oschina.net/ppppower/blog/36685

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值