Getting each character in a string and its frequency

Recommended Posts

Drakkcon    612
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.

Share this post

Share on other sites
Tron3k    660
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.

Share this post

Share on other sites
Oluseyi    2112
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).

Share this post

Share on other sites
Drakkcon    612
Thanks for the help both of you. I forgot about maps, and will try this approach now.

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now