Getting each character in a string and its frequency
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.
Here's an interesting C++ way to do this.
At the end you will have a map which maps characters to their frequencies.
#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 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).
This topic is closed to new replies.
Advertisement
Popular Topics
Advertisement