Getting each character in a string and its frequency

Started by
2 comments, last by Drakkcon 19 years, 6 months ago
I want to search a C++ string for a literal and its number of occurences. Basically, I've created a struct named literal, that has members 'frequency' and 'text'. I want to get every character used in a string (and put each in a vector), and the frequency of each (also put in a vector), and then create a vector of literals that adds these two bits of information. So the string 'Foobar' would give F, o, b, a, and r. And the frequency would be 1, 2, 1, 1, 1. For anyone who's wondering, I'm trying to use the Huffman encoding algorithm to create an encoding format.
Advertisement
Here's an interesting C++ way to do this.
#include <map>#include <string>using namespace std;void getFreq(string s, map<char, int> m) {    m.clear();    for (string::iterator i = s.begin(); i != s.end(); ++i) {        ++m[*i];    }}

At the end you will have a map which maps characters to their frequencies.
“[The clergy] believe that any portion of power confided to me, will be exerted in opposition to their schemes. And they believe rightly: for I have sworn upon the altar of God, eternal hostility against every form of tyranny over the mind of man” - Thomas Jefferson
The frequency chart is a one-to-one mapping of the text literal to its frequency. That should suggest the obvious:
std::map<char, size_t> freq_chart;
You can then simply iterate through the string, inserting or incrementing the frequency count into the mapping. Because iterators for std::map return a std::pair of the key and value, it's trivial to print out a frequency table (consider using a std::ostream_iterator, either to cout, a std::stringstream, or some other std::ostream-derived object, such as a std::ofstream).
Thanks for the help both of you. I forgot about maps, and will try this approach now.

This topic is closed to new replies.

Advertisement