[英]How to find the most repeated word?
如何使程序打印出最重復的單詞? 現在,它的打印如下:
輸入:蘋果香蕉蘋果蘋果
輸出:
蘋果出現了3次
香蕉出現了1次
int main() {
string words;
vector<string> stringHolder;
while (cin >> words)
{
stringHolder.push_back(words);
}
sort(stringHolder.begin(), stringHolder.end());
int vSize = stringHolder.size();
if (vSize == 0) {
cout << " no words ";
}
int wordCount = 1;
words = stringHolder[0];
for (int i = 1; i<vSize; i++) {
if (words != stringHolder[i]) {
cout << words << " appeared " << wordCount << " times" << endl;
wordCount = 0;
words = stringHolder[i];
}
wordCount++;
}
cout << words << " appeared " << wordCount << " times" << endl;
system("pause");
}
我會為此使用一個std::map
和一個std::set
:
#include <iostream>
#include <string>
#include <vector>
#include <map>
#include <set>
// typedef for a "word => count" map
using wordcountmap = std::map<std::string, int>;
// typedefs for making a sorted set
using wordcountpair = std::pair<std::string, int>;
using CompareFunc = bool(*)(const wordcountpair&, const wordcountpair&);
using wordcountset = std::set<wordcountpair, CompareFunc>;
wordcountmap make_wordcountmap(const std::vector<std::string>& words)
{
wordcountmap wcm;
// map::operator[] is used to access or
// insert specified element
for(const std::string& word : words) {
// std::string has a std::hash specialization
// https://en.cppreference.com/w/cpp/utility/hash
// calculating the hash for you
//
// If "word" does not exist in the map, it will be inserted
// with a default constructed value, which is 0 for an int.
++wcm[word];
}
return wcm;
}
wordcountset make_wordcountset(const wordcountmap& wcm) {
// populate the set using the maps iterators and provide a comparator
// lambda function that will sort the set in descending order
wordcountset wcs(
wcm.begin(),
wcm.end(),
[](const wordcountpair& a, const wordcountpair& b) {
return b.second==a.second ? b.first<a.first : b.second<a.second;
}
);
return wcs;
}
int main(int argc, char* argv[]) {
// put all command line arguments in a string vector
std::vector<std::string> args(argv+1, argv+argc);
// Your "word => count" map
wordcountmap MyWCM = make_wordcountmap(args);
// create a set of <word, count> pairs, sorted in count order.
wordcountset set_of_sorted_words = make_wordcountset(MyWCM);
// output the number of times the words appeared
for(const wordcountpair& element : set_of_sorted_words) {
// element.first is the "word" in the wordcountpair
// element.second is the "value" in the wordcountpair
std::cout << element.second << " " << element.first << "\n";
}
if(set_of_sorted_words.size())
std::cout << "The winner is " << (*set_of_sorted_words.begin()).first << "\n";
return 0;
}
輸出:
3 apple
1 banana
The winner is apple
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.