Search code examples
c++algorithmdictionaryasymptotic-complexityword-count

c++ finding same record in vector


Ihave a vector that contains monthyear

Jan2013 Jan2013 Jan2013 Jan2014 Jan2014 Jan2014 Jan2014 Feb2014 Feb2014

Basically what I want to do is to search through the vector, for every same record, group them together like e.g

total count for Jan2013 = 3; 
total count for Jan2014 = 4; 
total count for Feb2014 = 2;

Of course as we know, we can just simply write multiple if to solve it

        if(monthyear = "Jan2013")  {
            //add count   
        }

        if(monthyear = "Jan2014")  {
            //add count   
        }

        if(monthyear = "Feb2014")  {
            //add count   
        }

but no way a programmer is going code it in this way. what if there's additional monthyear march2014,april2014,may2014 all the way to dec2014 and jan2015-dec2015 and so on.

I don't think I should be adopting this kind of hard-coding method in the long run and looking for a more dynamic approach.

I not asking for codes, but just some steps and perhaps give me some hints on what c++ methods should I be researching on.

Thanks in advance


Solution

  • You can use std::map. For example

    std::map<std::string, size_t> m;
    
    for ( const std::string &s : v ) ++m[s];