c ++在向量中找到相同的记录

use*_*249 3 c++ algorithm map asymptotic-complexity word-count

我有一个包含一年的矢量

Jan2013 Jan2013 Jan2013 Jan2014 Jan2014 Jan2014 Jan2014 Feb2014 Feb2014

基本上我想要做的是搜索向量,对于每个相同的记录,将它们组合在一起,例如

total count for Jan2013 = 3; 
total count for Jan2014 = 4; 
total count for Feb2014 = 2;
Run Code Online (Sandbox Code Playgroud)

当然,正如我们所知,我们可以简单地编写多个if来解决它

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

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

        if(monthyear = "Feb2014")  {
            //add count   
        }
Run Code Online (Sandbox Code Playgroud)

但是程序员不会以这种方式编写代码.如果2014年3月,2014年4月,2014年5月到2015年1月和2015年1月至2015年15月还有额外的月份.

从长远来看,我不认为我应该采用这种硬编码方法,并寻找更具动态性的方法.

我不是要求代码,而只是一些步骤,或许可以给我一些关于我应该研究什么样的c ++方法的提示.

提前致谢

Vla*_*cow 10

你可以用std::map.例如

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

for ( const std::string &s : v ) ++m[s];
Run Code Online (Sandbox Code Playgroud)


Fre*_*son 5

我可能会做一个std::map<monthyear, int>.对于矢量的每个成员,递增该成员的地图.