Tuesday, July 28, 2009

What is the C++ algorithm for string frequency sort?

I need to sort an array of strings by frequency, with most frequently occurring words listed first.





Thanks in advance!

What is the C++ algorithm for string frequency sort?
If you have a vector of strings, use an STL map to map strings to their frequency. Then create a new vector of pairs where the first element is the frequency and the second is the string. Then use STL's sort algorithm to sort by the first element of the pair.





vector%26lt;string%26gt; input;


map%26lt;string, int%26gt; freq;


for (int i=0;i%26lt;input.size();i++) {


freq[input[i]]++;


}





vector%26lt; pair%26lt;int, string%26gt; %26gt; output;


for(map%26lt;string, int%26gt;::iterator it=freq.begin();it!=freq.end();it++) {


output.push_back( make_pair( (*it).second, (*it).first) );


}





sort(output.begin(), output.end());

edible flowers

No comments:

Post a Comment