Home

red floyd wrote:

> Kai-Uwe Bux wrote:
>> Erik Wikström wrote:
>>
>>> On 2007-09-29 13:41, subramanian100in@yahoo.com, India wrote:
>>>> As a beginner in C++, I have attempted the C++ solution for the
>>>> following:
>>>>
>>>> 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 assume that we should NOT sort the words first. Instead sort
>>>> in decreasing order as per frequency.)
>>>>
>>>> Following is my C++ solution which works fine. Kindly suggest better
>>>> way of doing it.
>>>>
>>>> #include <iostream>
>>>> #include <vector>
>>>> #include <string>
>>>> #include <utility>
>>>> #include <algorithm>
>>> I have not looked at your code, but for this you should only need to
>>> include <iostream>, <string> and <map>.
>>
>> Really? You are probably thinking of using
>>
>> std::map< std::string, unsigned >
>>
>
> // comparator for *DECREASING* order
> struct compare {
> bool operator()(const std::pair<string, unsigned>& lhs,
> const std::pair<string, unsigned& rhs) const
> {
> return lhs.second > rhs.second;
> }
> };
>
> std::map<std::string, unsigned> words_and_freqs;
>
> // fill map, then do this. Creates a set sorted by frequency
>
> std::set<std::pair<std::string, unsigned> >
> freqs_first(words_and_freqs.begin(), words_and_freqs.end(),
> compare());
>
> the set is sorted by the frequency in descending order.

And, if I see this correctly, it will contain exactly one word for each
frequency, because two pairs with equal frequency counts will be treated as
comparing equal by std::set<>.

However, that can be fixed, in which case you would throw in the header
<set> instead of <vector> and <algorithm>. Well, that's fine, too.


Best

Kai-Uwe Bux

previous
next

A dumb question about a class
Re: WebBased Vector 2D Graphics
Re: compilation error using ofstream
Re: "Variable variable name" or "variable lvalue"
Re: Python Database Apps
odszkodowania
regeneracja akumulatorów
zapiekanki z serem
pozycjonowanie stron piekary śląskie
Zdrowa zywnosc