I'd use a std::map
and a std::set
for that:
#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 << "
";
}
if(set_of_sorted_words.size())
std::cout << "The winner is " << (*set_of_sorted_words.begin()).first << "
";
return 0;
}
Output:
3 apple
1 banana
The winner is apple
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…