Accelerated C++<4-5>

这是一个C++程序,用于从输入流中读取单词,存储到向量中,并计算每个单词的数量。程序首先清除向量,然后逐个读取单词并添加。在主函数中,对单词进行排序,遍历以计算每个单词的出现次数。

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

//编写一个函数以从输入流读单词,将读到的单词存储在一个向量中。利用这个函数编写一个程序以计算输入的单词的数目以及每一个单词所出现的次数。



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


using namespace std;


istream& read_words(istream& in, vector<string>& words) {
  if (in) {
    words.clear();
    string word;
    
    while (in >> word)
      words.push_back(word);
    
    in.clear();
  }
  
  return in;
}


int main() {
  vector<string> words;


  read_words(cin, words);


  cout << "Num of words: " << words.size() << endl;


  sort(words.begin(), words.end());


  string prev_word = "";
  int count = 0;


  for (vector<string>::size_type i = 0; i < words.size(); ++i) {
    if (words[i] != prev_word) {
      if (prev_word != "")
cout << prev_word << " appeared " << count << " times" << endl;


      prev_word = words[i];
      count = 1;
    }
    else
      ++count;
  }


  cout << prev_word << " appeared " << count << " times" << endl;


  return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值