week 1-2:c++ 文本文件单词排序+单词频次计数

设有文本文件(words.txt)的内容为英文单词(单词都由小写字母构成)构成的序列(单词之间用空白符号分隔,空格、跳格('\t')、换行等都是空白符号),编写程序实现以下功能:

(1)[80分]将words.txt中的所有单词按照字典序排列;

(2)[20分]统计不同单词的数目(即共有多少个互不相同的单词),以及每个单词出现的次数。

两个功能都实现了,编译运行后会输出排序结果和频次计数结果。

#include <iostream>
#include <fstream>
#include <map>
#include <set>
#include <vector>
#include <algorithm>

int main() {
    std::ifstream file("words.txt");
    if (!file.is_open()) {
        std::cerr << "Error opening file." << std::endl;
        return 1;
    }

    std::map<std::string, int> wordCount;
    std::set<std::string> uniqueWords;
    std::string word;

    while (file >> word) {
        uniqueWords.insert(word);
        wordCount[word]++;
    }

    file.close();

    //首先给单词排序
    std::vector<std::string> sortedWords(uniqueWords.begin(), uniqueWords.end());
    std::sort(sortedWords.begin(), sortedWords.end());

    //输出
    std::cout << "Words in dictionary order:" << std::endl;
    for (const std::string& w : sortedWords) {
        std::cout << w << std::endl;
    }

    //计算频次
    std::cout << "\nNumber of unique words: " << uniqueWords.size() << std::endl;
    std::cout << "\nOccurrences of each word:" << std::endl;
    for (const auto& pair : wordCount) {
        std::cout << pair.first << ": " << pair.second << std::endl;
    }

    return 0;
}

  • 4
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值