python集合的C++等价物是什么.计数器
What is the C++ equivalent of python collections.Counter?
pythoncollections.Counter
对象跟踪对象的计数。
>> from collections import Counter
>> myC = Counter()
>> myC.update("cat")
>> myC.update("cat")
>> myC["dogs"] = 8
>> myC["lizards"] = 0
>> print(myC)
{"cat": 2, "dogs": 8, "lizards": 0}
有没有一个类似的C++对象,我可以很容易地跟踪某个类型的出现次数?也许是map
到string
?请记住,以上只是一个例子,在C++中,这将推广到其他类型。
您可以使用类似于的std::map
#include <iostream>
#include <map>
int main()
{
std::map<std::string,int> counter;
counter["dog"] = 8;
counter["cat"]++;
counter["cat"]++;
counter["1"] = 0;
for (auto pair : counter) {
cout << pair.first << ":" << pair.second << std::endl;
}
}
输出:
1:0
cat:2
dog:8
如果您想要恒定的平均查找复杂度(就像使用collections.Counter一样(,可以使用std::unordered_map。std::map"通常实现为红黑树",因此查找的复杂度是容器大小的对数。而且我们在Python的内置库中没有红黑树实现。
std::unordered_map<std::string,int> counter;
counter["dog"] = 8;
counter["cat"]++;
counter["cat"]++;
counter["1"] = 0;
for (auto pair : counter) {
cout << pair.first << ":" << pair.second << std::endl;
}
您可以使用CppCounter:
#include <iostream>
#include "counter.hpp"
int main() {
collection::Counter<std::string> counter;
++counter["cat"];
++counter["cat"];
counter["dogs"] = 8;
counter["lizards"] = 0;
std::cout << "{ ";
for (const auto& it: counter) {
std::cout << """ << it.first << "":" << it.second.value() << " ";
}
std::cout << "}" << std::endl;
}
CppCounter是集合的C++实现。计数器:https://gitlab.com/miyamoto128/cppcounter.它是在undered_map之上编写的,易于使用。
我可以补充一下,我是作者;(
Python3代码:
import collections
stringlist = ["Cat","Cat","Cat","Dog","Dog","Lizard"]
counterinstance = collections.Counter(stringlist)
for key,value in counterinstance.items():
print(key,":",value)
C++代码:
#include <iostream>
#include <unordered_map>
#include <vector>
using namespace std;
int main()
{
unordered_map <string,int> counter;
vector<string> stringVector {"Cat","Cat","Cat","Dog","Dog","Lizard"};
for (auto stringval: stringVector)
{
if (counter.find(stringval) == counter.end()) // if key is NOT present already
{
counter[stringval] = 1; // initialize the key with value 1
}
else
{
counter[stringval]++; // key is already present, increment the value by 1
}
}
for (auto keyvaluepair : counter)
{
// .first to access key, .second to access value
cout << keyvaluepair.first << ":" << keyvaluepair.second << endl;
}
return 0;
}
输出:
Lizard:1
Cat:3
Dog:2
相关文章:
- 为不同配置设置MSVC_RUNTIME_LIBRARY的正确方法是什么
- C++避免重复声明的语法是什么
- 在C++中,将大的无符号浮点数四舍五入为整数的最佳方法是什么
- 实现无开销push_back的最佳方法是什么
- C++从另一个类访问公共静态向量的正确方法是什么
- "throw expression code" 1e7 >返回 d 是什么?投掷标准::overflow_error( "too big" ) : d;意味 着?
- C++中名称篡改的目的是什么
- 在 c++ 中拥有一组结构的正确方法是什么?
- 这个指针和内存代码打印是什么?我不知道是打印垃圾还是如何打印我需要的值
- 是什么阻止DOMTimerCoordinator::NextID进入无休止的循环
- 派生类销毁的最佳实践是什么
- 这个语法std::class<>{}(arg1, arg2) 在C++中是什么意思?
- 通过JNI传递数据数组的最快方法是什么
- "using namespace std;"在C++的作用是什么?
- 在两台机器之间进行时间戳的最佳c++chrono函数是什么
- 文件系统:复制功能的速度秘诀是什么
- 用常见虚拟函数实现的任意组合来实现派生类的正确方法是什么
- 使用QQuickFramebufferObject时同步数据的最佳方式是什么
- python集合的C++等价物是什么.计数器
- 这些时间计数器细化语句的目的是什么