c++ - 是否有一种有效的方法来检查正在使用的字母?
问题描述
假设我有一个 string string str;
,其中包含任意数量的字母,我想计算字符串中每个字母的数量。例如,单词"Example"
有 2 'e'
、 1 'x'
、 1 'a'
、 1 'm'
、 1'p'
和 1 'l'
。有没有比这更有效的方法来检查每个字母?
for (int i = 0; i < str.length(); i++)
{
if (str.at(i) == 'a')
{
//variable which keeps track of a ++
}...
//25 more of that for each other letter
}
感觉必须有一种更有效的方法来做到这一点,但我不知道怎么做。请赐教。
解决方案
您可以使用std::map
例如:
#include <map>
std::map<char, std::size_t> mCount{};
for (auto ch : str)
{
++mCount[ch];
}
使用 a std::array
(其优点是数据在内存中是连续的,从而提高缓存性能)您可以编写:
#include <array>
#include <limits>
constexpr auto nNumChars = static_cast<std::size_t>(std::numeric_limits<unsigned char>::max()) + 1;
std::array<std::size_t, nNumChars> arCounts{};
for (auto ch : str) {
++arCounts[static_cast<unsigned char>(ch)];
}
推荐阅读
- keras - 对于 batch_size>1,Keras(分割模型)的形状不兼容问题
- java - 如何在循环循环后获取用户输入以允许另一个输入?
- python - 当涉及“r”和“/”时,正则表达式会变得非常混乱
- javascript - 找到数组中消失的所有数字
- angular - 流式传输音频文件时如何设置 HTTP-Header?
- python - pyautogui.keyDown 和 pyautogui.keyUp 不能在 Mac 上使用 Python
- flutter - Flutter:RichText 不适用于主题
- kotlin - 带有协程的 Kotlin 中的 Nio http 服务器
- https - 有什么方法可以将位于 LAN(不是 Localhost)中的系统 Ip 设置为 Https 协议?
- python - tkinter 检查按钮值打印