c++ - 是否有另一种方法可以在不使用 if 语句的情况下有条件地增加数组值?C++
问题描述
如果有一个数组,
int amounts[26] = { 0, 0, 0, ...};
并且我希望数组的每个数字代表不同字符串的数量,例如在给定字符串中找到amounts[0] = amount;
的'a'
's ,无论如何是否可以在不使用 if 语句的情况下增加每个值?
伪代码示例:
int amounts[26] = { 0, 0, 0, ...};
string word = "blahblah";
loop here to check and increment amounts[0] based on amount of 'a's in string
repeat loop for each letter in word.`
在循环结束时,根据字符串 word,数量应如下所示:
amounts[0] = 2 ('a')
amounts[1] = 2 ('b')
amounts[2] = 0 ('c')
// etc
解决方案
给定你的例子,假设整个字符串是小写和有效字符,有一个相当简单的解决方案(也就是说,你处理验证)
for (int i = 0; i < word.size(); i++) {
amounts[word[i]-'a']++; // you can also do a pre-increment if you want
}
推荐阅读
- javascript - 自定义 api 格式的返回列表问题
- python - Scrapy:如何使用元在方法之间传递项目
- homebrew - 我应该如何处理密码?
- sql-server - 将具有 20 个表的 MS SQL DB 编辑为 1 个表而不丢失数据
- javascript - InitializeGrid 中的错误在哪里?它返回错误的索引
- mysql - 获取排行榜数据时,MySQL '子查询返回超过 1 行'
- c# - 如何使用 lock 语句避免 null?
- windows - netcat windows 在 UDP 上侦听密码
- ethereum - 无法使用 truffle compile 命令编译智能合约
- c# - 在 Windows AS 普通用户中请求以管理员身份启动进程