//编写一个程序用于计算在它的输入中每个不同的单词所出现的次数。
Hint
Use a vector to store the words, then sort the vector. That way you can count the words, in order, as you iterate over the vector.
Solution
This solution stores the words in a vector, sorts the vector, then retrieves each word from the vector and increments a count each time the same word is retrieved from the vector. When a word is retrieved from the vector that does not match the previous word, the count is reported for the last word, then reset for the new word.
#include<string>
#include<algorithm>
#include<vector>
using namespace std;
int main(){
//请求读入单词
cout<<"please enter a few words,followed by end-of-file: "<<endl;vector<string>words;
string word;
//将读到的单词放入容器中
while(cin>>word)words.push_back(word);
typedef vector<string>::size_type vec_sz;
vec_sz size=words.size();
if(size==0)
{
cout<<endl<<"you didn't enter any word.please try again."<<endl;
return 1;
}
sort(words.begin(),words.end());
string current_word;
int count;
current_word=words[0];
count=1;
for(vec_sz current_index=1; current_index<size; ++current_index)
{
//如果容器内索引处单词与当前不匹配则输出当前单词(输出不相等的单词),并重置计数值为0,
if(current_word!=words[current_index]){
cout<<"the words\""<<current_word<<"\"appears:"<<count<<" times."<<endl;
current_word=words[current_index];
count=0;
}
//相等则计数值加1
++count;}
cout<<"the words\""<<current_word<<"\"appears:"<<count<<" times."<<endl;
return 0;
}