确定向量中最频繁的字符元素<char>? [英] Determining most freq char element in a vector<char>?

查看:22
本文介绍了确定向量中最频繁的字符元素<char>?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试确定以字符为元素的向量中出现频率最高的字符.

I am trying to determine the most frequent character in a vector that has chars as its elements.

我正在考虑这样做:

  • 循环遍历向量并创建一个映射,其中键是向量中找到的唯一字符.相应的值将是该字符频率的整数计数.
  • 遍历向量中的所有元素后,地图将包含所有字符频率.因此,我将不得不找到哪个键具有最高值,因此确定最多向量中的频繁字符.

虽然这看起来很复杂,因此我想知道是否有人可以建议这种方法在性能/良好编码方面是否被认为是可接受的"

This seems quite convoluted though, thus I was wondering if someone could suggest if this method would be considered 'acceptable' in terms of performance/good coding

能否以更好的方式做到这一点?

推荐答案

如果你只使用常规的 ascii 字符,你可以使解决方案更快一点——而不是使用地图,使用大小为 256 的数组并计算数组单元格 count[x] 中具有给定代码 'x' 的字符的出现次数.这将从您的解决方案中删除对数(256),从而使其更快.我不认为在优化这个算法方面可以做更多的事情.

If you are only using regular ascii characters, you can make the solution a bit faster - instead of using a map, use an array of size 256 and count the occurrences of the character with a given code 'x' in the array cell count[x]. This will remove an logarithm(256) from your solution and thus will make it a bit faster. I do not think much more can be done with respect to optimization of this algorithm.

这篇关于确定向量中最频繁的字符元素<char>?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆