S
subramanian100in
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>
using namespace std;
typedef pair<int, string> is;
bool cmp_fn(is arg1, is arg2)
{
return (arg2.first < arg1.first) ? true : false;
}
void print(const is & arg)
{
cout << arg.second << ": " << arg.first << endl;
}
int main()
{
vector<string> unique_words;
vector<is> v;
string word;
while (cin >> word)
{
if (find(unique_words.begin(), unique_words.end(),
word) == unique_words.end())
{
unique_words.push_back(word);
v.push_back(make_pair(1, word));
}
else
{
for (vector<is>::iterator i = v.begin(); i !=
v.end(); ++i)
if (i->second == word)
{
++i->first;
break;
}
}
}
sort(v.begin(), v.end(), cmp_fn);
for_each(v.begin(), v.end(), print);
return 0;
}
Kindly help.
Thanks
V.Subramanian
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>
using namespace std;
typedef pair<int, string> is;
bool cmp_fn(is arg1, is arg2)
{
return (arg2.first < arg1.first) ? true : false;
}
void print(const is & arg)
{
cout << arg.second << ": " << arg.first << endl;
}
int main()
{
vector<string> unique_words;
vector<is> v;
string word;
while (cin >> word)
{
if (find(unique_words.begin(), unique_words.end(),
word) == unique_words.end())
{
unique_words.push_back(word);
v.push_back(make_pair(1, word));
}
else
{
for (vector<is>::iterator i = v.begin(); i !=
v.end(); ++i)
if (i->second == word)
{
++i->first;
break;
}
}
}
sort(v.begin(), v.end(), cmp_fn);
for_each(v.begin(), v.end(), print);
return 0;
}
Kindly help.
Thanks
V.Subramanian