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.
            Asked
            
        
        
            Active
            
        
            Viewed 532 times
        
    1
            
            
         
    
    
        Lightness Races in Orbit
        
- 378,754
- 76
- 643
- 1,055
 
    
    
        bobthemac
        
- 1,172
- 6
- 26
- 59
- 
                    Which C++ book are you using? – Lightness Races in Orbit Mar 08 '12 at 11:28
- 
                    [Good timing](http://stackoverflow.com/questions/9616929/convert-array-to-new-array) – Lightness Races in Orbit Mar 08 '12 at 11:28
- 
                    i am not using a book i say it on this website [link](http://compgroups.net/comp.soft-sys.matlab/Counting-Number-of-Occurrences-of-Each-Number-in-a-Vector) – bobthemac Mar 08 '12 at 11:29
- 
                    3@bobthemac That link isn’t about C++ at all. – Konrad Rudolph Mar 08 '12 at 11:31
- 
                    And no, you cannot use `unique`, however you can use `count` (if looking for a specific word) or even a simple iteration through the vector with an insert into a map. – Nim Mar 08 '12 at 11:33
- 
                    [Begin here](http://jcatki.no-ip.org/fncpp/Resources). Come back when you've read it. We expect prior research on SO. Good luck! – Lightness Races in Orbit Mar 08 '12 at 11:34
- 
                    And that site you linked to is about Matlab, not C++... – Lightness Races in Orbit Mar 08 '12 at 11:35
2 Answers
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
- 
                    1frequency should be std::cout << i->first << ": " << i->second / vec.size() << "\n"; – CapelliC Mar 08 '12 at 11:36
- 
                    
- 
                    @chac Uh … you’re of course right. I misread the question, is all. – Konrad Rudolph Mar 08 '12 at 11:45
