确定在矢量&lt最频率炭元素;焦炭>? [英] Determining most freq char element in a vector<char>?

查看:164
本文介绍了确定在矢量&lt最频率炭元素;焦炭>?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图确定最频繁的字符在具有字符作为其元素的矢量。

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

我想这样做的:

  • 通过矢量循环并创建映射,其中一个关键是在载体中发现了一个独特的字符。对应的值将是炭的频率的整数计数。
  • 在我穿过向量的所有元素都走了,地图上会 包含所有字符的频率。因此,我便要找到 哪个键具有最高值,因此,确定最 频繁的角色,在载体中。
  • looping through the vector and creating a map, where a key would be a unique char found in the vector. The corresponding value would be the integer count of the frequency of that char.
  • After I have gone through all elements in the vector, the map will contain all character frequencies. Thus I will then have to find which key had the highest value and therefore determine the most frequent character in the vector.

这似乎很令人费解,虽然,所以我想知道,如果有人可以建议如果这种方法会被认为是可以接受的。在性能方面/良好的编码

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的数组和计数出现的字符与数组单元格给定的code'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.

这篇关于确定在矢量&lt最频率炭元素;焦炭>?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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