Re: C++ solution for K & R(2nd Ed) Ex.6-4 - better solution needed
On Sep 30, 7:10 am, Erik Wikstr=F6m <Erik-wikst...@telia.com> wrote:
It is a good solution, however it does not take full advantage of the
containers provided in the standard library. For example unique_words
should probably be a set instead of a vector. Using the vector to store
both frequency and word have some advantages over a map, since it can be
sorted by both frequency and word making it useful in both stages of the
program. My only complaint is that your solution requires you to write
more code than one that takes better advantage of the standard
containers, it will however probably perform better and sometimes that
is more important.
My suggestion would have been to use first a map to read in the words
and counting their frequency, and then construct a multimap sorted by
frequency which is then printed:
#include <iostream>
#include <string>
#include <map>
int main()
{
std::map<std::string, size_t> words;
// Read words and count frequency
std::string w;
while (std::cin >> w)
{
++words[w];
}
// Construct multimap, notice the use of greater to sort it in
// decending order instead of ascending
std::multimap<size_t, std::string, std::greater<size_t> > freq;
std::map<std::string, size_t>::iterator i;
for (i = words.begin(); i != words.end(); ++i)
{
freq.insert(std::make_pair(i->second, i->first));
}
// Print, someone can probably come up with a way to use std::copy
// to print it instead, but I prefer an explicit loop
std::multimap<size_t, std::string, std::greater<size_t>>::iterator j;
for (j = freq.begin(); j != freq.end(); ++j)
{
std::cout << j->first << "\t" << j->second << "\n";
}
}
--
Erik Wikstr=F6m
Let me restate the exercise:
Consider the Ex. 6-4 in K & R(ANSI C) 2nd Edition in Page 143 :
Write a program that prints the distinct words in its input sorted
into descending order of frequency of occurrence. Precede each word by
its count.
(Here I assumed that we should NOT sort the words first. Instead sort
in decreasing order as per frequency.)
If we use a set or a map, won't it store input words in sorted
manner ? If so, it is not accepted in this problem. Order of input
words can be changed only for sorting by their frequency. That is why
I had to use vector. Correct me if I am wrong.
However thanks for giving a simple solution and I will use it if there
is no condition imposed on the sorting of words(ie the words may or
may not maintain their input order).
Thanks
V.Subramanian