2016-03-15 48 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是的。 –