Accelerated C++<3-3>

本文介绍了一个简单的程序设计方法,该程序能够接收用户输入的一系列单词,并统计每个不同单词出现的次数。通过使用C++标准库中的vector容器来存储单词,然后对其进行排序,从而实现了高效的单词计数。

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

//编写一个程序用于计算在它的输入中每个不同的单词所出现的次数。


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<iostream>
#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;
}


评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值