2016-03-15 27 views
1

我有strings一個矢量:容器中的元素多重性?

std::vector<std::string> data; 

我需要一個返回std::map<std::string, int>一個algorihtm,存儲data每個不同std::string其多重性(它顯示了多少次重複在data)沿。

這是用C++標準庫文件實現的嗎?哪裏?

如果不是,你能提出一個有效的算法來做到這一點嗎?

評論:這相當於Counter在Python中的作用。我正在尋找一個C++實現。

+0

我在想這個。興奮的回答 –

+0

@NathanOliver它不是重複的。它是相似的,但數據類型是不同的。我也很喜歡循環。我認爲這是一個不同的問題 – becko

+0

爲什麼矢量中的數據類型很重要? – NathanOliver

回答

1
#include <iostream> 
#include <vector> 
#include <string> 
#include <map> 

std::map<std::string, int> counts(const std::vector<std::string>& v) 
{ 
    std::map<std::string, int> result; 
    for (auto const& s : v) { 
     ++result[s]; 
    } 
    return result; 
} 

int main() 
{ 
    auto m = counts({"a", "a", "b", "c", "c", "c" }); 
    for (auto const& e : m) 
    { 
     std::cout << e.first << " : " << e.second << std::endl; 
    } 
    return 0; 
} 

預計業績:

a : 2 
b : 1 
c : 3 

說明:

用的std ::地圖<>,操作[K]將搜索項中的地圖匹配鍵k。如果未找到,則將(k,v)插入到映射中,其中v是V的默認初始化值。在任一種情況下,無論是否找到,都會返回對應於k的V的引用。

4

你可以只寫

std::vector<std::string> data; 
std::map<std::string, int> m; 

//... 

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

所以這將創建新的,如果沒有找到? –

+0

@FirstStep是的。 –