c ++如何巧妙地计算元素频率? [英] c++ How to count element frequency smartly?
本文介绍了c ++如何巧妙地计算元素频率?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在获取数组元素 [2 2 2 3 4 5 6]我想要存储每个元素的数量?如何以最好的方式做 stl 或类似的事情?
I am getting array element [2 2 2 3 4 5 6] I want the count of each element stored ? How to do in best way stl or something like that?
推荐答案
如果您知道值的可能范围很小且接近 0:
If you know that the possible range of values is small and near 0:
std::array<size_t, max_value> histogram;
否则
std::/*unordered_*/map<int, size_t> histogram;
然后
for (int value : elements) { ++histogram[value]; }
这篇关于c ++如何巧妙地计算元素频率?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文