容器中的元素多重性
Element multiplicities in container?
我有一个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 的引用。
相关文章:
- 更改多重映射容器中所有元素的键值
- 查找数组中指示性较大但数组中值较小的元素
- 如何使用谷歌测试检查两个枚举类元素的相等性?
- 需要帮助编写一个小程序来将循环乘以 n 个元素和 k 个多重性
- 多重继承和访问不明确的元素
- 多重映射的每个元素是否同时包含键和值
- 使用多重性函数与 in C++ 联合两个链表
- 如何检查 O(N) 时间复杂度的多重集中是否有 2 个或更多元素具有相同的值
- 转换性元素::元素
- 多重映射是否保证广告顺序与其初始值设定项中给出的元素顺序匹配
- C++检查字符串元素的相等性
- 如何在 cpp 中定义挥发性元素的映射
- c++:多态性+多重继承顺序.继承顺序是否重要
- C++递减单字节(易失性)数组的元素不是原子!为什么?(还有:如何在Atmel AVR mcus/Arduino中强制原
- 从大小为n的r个元素生成幂多重集
- C++多重继承多态性
- 容器中的元素多重性
- 具有多态性的多重受保护继承
- 检查数组中元素的相等性 - c++
- 如何在素数因子分解中求素数因子的多重性