2014-01-08 26 views
3

IHAVE一個載體,它包含monthyearC++找到相同的記錄在矢量

Jan2013 Jan2013 Jan2013 Jan2014 Jan2014 Jan2014 Jan2014 Feb2014 Feb2014

基本上就是我想要做的就是通過搜索對於每個相同的記錄,該載體將它們組合在一起,如 ,例如

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

當然,因爲我們知道,我們只要簡單地寫多,如果要解決它

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

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

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

,但絕不是一個程序員是怎麼回事代碼它以這種方式。 如果還有額外的年份,2014年4月,2014年4月,2014年5月,一直到2014年12月 和2015年1月 - 2015年12月等。

我不認爲我應該在長期運行中採用這種硬編碼方法,並尋找更動態的方法。

我不要求代碼,但只是一些步驟,也許給我一些提示,我應該研究什麼樣的C++方法。

在此先感謝

+4

請務必在if語句中使用'monthyear ==「... 2014」'。 – lcs

回答

10

您可以使用std::map。例如

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

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

感謝我將查找上的std ::地圖 – user2947249

+1

下面是一個例子 的#include 的#include 的#include 的#include INT主() { \t的std ::矢量 v = \t { \t \t 「Jan2013」​​, 「Jan2013」​​, 「Jan2013」​​, \t \t 「Jan2014」, 「Jan2014」, 「Jan2014」, 「Jan2014」 \t \t「Feb2014」,「Feb2014」 \t}; \t \t std :: map m; \t \t for(const std :: string&s:v)++ m [s]; \t \t for(auto p:m)std :: cout << p.first <<'\ t'<< p.second << std :: endl; \t \t return 0; } –

+0

再次感謝你 – user2947249

5

我可能會做一個std::map<monthyear, int>。對於矢量的每個成員,增加該地圖的成員。

+0

謝謝我會查找std :: map – user2947249

+0

@ user2947249:來自莫斯科的弗拉德給了你一個很好的例子。 –

1

只是爲了完整:@VladfromMoscow的解決方案對於您對輸入知之甚少的一般情況是最佳選擇。對於長度爲N的輸入,它的複雜性爲O(N log N)

等效地,您可以先將輸入排序在O(N log N)中,然後在O(N)中對排序的輸入進行迭代並將計數存儲在std::vector<std::pair<std::string, int>>中。

但是,如果你有對您輸入的範圍先驗信息(比如你肯定知道從2013年1月持續到2014年1月),也可以直接在你的輸入運行和更新預 - 分配std::vector<std::pair<std::string, int>>O(N)複雜性。

+0

謝謝你的信息 – user2947249