在看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;
}