1

I want to to get the frequency of words stored in a vector. I have Googled my question numerous times and not go something that would work for me. I have found a site where someone says to use the unique command to count the frequency of words but I can not find any examples of how this is done.

Lightness Races in Orbit
  • 378,754
  • 76
  • 643
  • 1,055
bobthemac
  • 1,172
  • 6
  • 26
  • 59

2 Answers2

6

Use a map<string, unsigned> to create a histogram:

using std::string;
using std::map;
using std::vector;

typedef map<string, unsigned> counts_t;

// Create the histogram
counts_t histogram;
for (vector<string>::const_iterator i = vec.begin(); i != vec.end(); ++i)
    ++histogram[*i];

// ... and display it.
for (counts_t::const_iterator i = histogram.begin(); i != histogram.end(); ++i) {
    double freq = static_cast<double>(i->second) / vec.size();
    std::cout << i->first << ": " << freq << "\n";
}
Konrad Rudolph
  • 530,221
  • 131
  • 937
  • 1,214
1

Doesn't use unique, but for word counting it's hard to beat a trie or any of its derivates, both in terms of memory usage & speed.

Ylisar
  • 4,293
  • 21
  • 27