设有文本文件(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;
}