I am doing some C++ exercises again, and ran into trouble.
Exercise text:
7-1. Extend the program from ยง7.2/124 to produce its output sorted by occurrence count. That is, the output should group all the words that occur once, followed by those that occur twice, and so on.
The Exercise itself is:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
#include <map>
#include <iostream>
usingnamespace std;
int main()
{
string s;
map<string, int> counters; // store each word and an associated counter
// read the input, keeping track of each word and how often we see it
while (cin >> s)
++counters[s];
// write the words and associated counts
for (map<string, int>::const_iterator it = counters.begin();
it != counters.end(); ++it) {
cout << it->first << "\t" << it->second << endl;
}
return 0;
}
1. Can I use predicate to order map by values? In current exercise - by int values.
2. Should I just manipulate the output?
3. Can anyone give me some solutions? If possible
then by using predicate on map directly using the form map<K, V> m(cmp).
#include <map>
#include <iostream>
usingnamespace std;
//Return iterator pointing to the map element with maximum value
map<string, int>::const_iterator findmax(map<string, int> counters)
{
map<string, int>::const_iterator newmax = counters.begin();
for (map<string, int>::const_iterator it = counters.begin();
it != counters.end(); ++it) {
if(newmax->second < it->second){
newmax = it;
}
}
return newmax;
}
int main()
{
string s;
map<string, int> counters; // store each word and an associated counter
// read the input, keeping track of each word and how often we see it
while (cin >> s)
++counters[s];
map<string, int>::const_iterator maximum;
//find the maximum value in the map
maximum = findmax(counters);
//The first for loop
// i points to the next value
for (map<string, int>::size_type i = 1; i <= maximum->second; ++i) {
//The second for loop
//Find all elements in the map that have a value that corresponds to i
for (map<string, int>::const_iterator it = counters.begin();
it != counters.end(); ++it) {
if(it->second == i)
cout << it->first << "\t" << it->second << endl;
}
}
return 0;
}