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

Recommended Answers

All 3 Replies

Sounds like a good place to use a map:

vector<string> v =
{
    "Jan2013",
    "Jan2013",
    "Jan2013",
    "Jan2014",
    "Jan2014",
    "Jan2014",
    "Jan2014",
    "Feb2014",
    "Feb2014"
};
map<string, int> freq;

// Loop through the vector
for (auto x : v)
{
    ++freq[*x];
}

for (auto x : freq)
{
    cout << "total count for " << x.first << " = " << x.second << '\n';
}

thanks for your snippet.

Got beat to the answer. Ignore post.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.