首页 > 解决方案 > 是否有另一种方法可以在不使用 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

标签: c++arraysloops

解决方案


给定你的例子,假设整个字符串是小写和有效字符,有一个相当简单的解决方案(也就是说,你处理验证)

for (int i = 0; i < word.size(); i++) {
    amounts[word[i]-'a']++; // you can also do a pre-increment if you want
}

推荐阅读