容器中的元素多重性

Element multiplicities in container?

本文关键字:元素 多重性      更新时间:2023-10-16

我有一个strings向量:

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

我需要一个返回std::map<std::string, int>的算法,将每个不同的std::string存储在data中,以及它的多重性(它在data中重复了多少次)。

这是否C++标准库中实现?哪里?

如果不是,你能提出一个有效的算法来做到这一点吗?

评论:这相当于Counter在Python中所做的。我正在寻找一个C++实现。

你可以写

std::vector<std::string> data;
std::map<std::string, int> m;
//...
for ( const std::string &s : data ) ++m[s];
#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::map<>,运算符 [k] 将在映射中搜索与键 K 匹配的项目。如果未找到,则 (k,v) 插入到映射中,其中 v 是 V 的默认初始化值。在任何一种情况下,无论是否找到,都会返回对对应于 k 的 V 的引用。