Вопрос

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

Это было полезно?

Решение

You can use std::map. For example

std::map<std::string, size_t> m;

for ( const std::string &s : v ) ++m[s];

Другие советы

I'd probably do a std::map<monthyear, int>. For each member of your vector, increment that member of the map.

Just for completeness: the solution by @VladfromMoscow is optimal for the general case in which you have little knowledge about your input. It is of O(N log N) complexity for an input of length N.

Equivalently, you can first sort your input in O(N log N), and then iterate in O(N) over the sorted input and store the counts in a std::vector<std::pair<std::string, int>>.

However, if you have a priori information on the range of your input (say you know for sure it runs from Jan 2013 until Jan 2014), you can also directly run over your input and update a pre-allocated std::vector<std::pair<std::string, int>> in O(N) complexity.

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top