The exercise (8 of chapter 21 of the book PPP) says:
Take the word-frequency example from ยง21.6.1 and modify it to output its lines in order of frequency (rather than in lexicographical order). An example line would be 3: C++ rather than C++: 3.
I'm not very sure about the exact intention of the exercise, but one code is this:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27
|
#include <iostream>
#include <map>
#include <string>
int main()
{
std::map<std::string,int> words;
std::cout << "Enter string values for the map. Enter ctrl+z at the end.\n";
for (std::string s; std::cin >> s;)
++words[s];
// To get rid of ctrl+z flags settings
std::cin.ignore(INT_MAX, '\n');
std::cin.clear();
std::map<int, std::string> nums;
for (const auto& w : words)
nums.insert({ w.second, w.first });
std::cout << "The values based on frequency order are\n";
for (auto iter = nums.rbegin(); iter != nums.rend(); ++iter)
std::cout << iter->first << ": " << iter->second << '\n';
std::cout << '\n';
return 0;
}
| |
The output for the input:
one three two three is:
which is logical since the
key in
std::map is unique. But I assume that the intention has been something like:
for the output. What are your ideas about the exercise, please?
Of course, I can use two vectors one for storing
int and the other for storing
string values and play with them so that the latter output is printed as the result, but that'd increase the complexity of the project unreasonably likely!
Mostly when I'm coding for an exercise I encounter this trouble that what is the intention of the exercise or what result is meant by it exactly!