c++统计输入中不同单词所出现的次数

在看accelerated c++第三章的练习3-3时,要求“编写一个程序用于计算在它的输入中每个不同的单词所出现的次数”,最简单的方法是用标准库的map容器来实现,可以定义一个map<string,int>。在这里,我使用了两个vector容器来实现:

#include <iostream>
#include <vector>
#include <string>

using std::cout;
using std::cin;
using std::endl;
using std::string;
using std::vector;

int _tmain(int argc, _TCHAR* argv[])
{
	string word;
	vector<string> words;  //存储单词
	vector<int> cnt_word;  //存储单词出现次数

	cout<<"Please input words(Ctrl+z to end):"<<endl;
	while (cin>>word) {
		bool same_word = false;
		for (int i = 0;i != words.size();i++) {
			if (word == words[i]) {
				cnt_word[i]++;  //统计次数加1
				same_word = true;
				break;
			}
		}
		if (same_word == false) {  //没有找到相同的单词
			words.push_back(word);
			cnt_word.push_back(1);  //出现次数赋值为1
		}
	}

	cout<<"words"<<"\tcount"<<endl;
	for (int i = 0;i != words.size();i++) {
		cout<<words[i]<<"\t"<<cnt_word[i]<<endl;
	}

	return 0;
}

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值