检查值是否存在于数组的所有索引中

3

我有一个大小为5的字符数组,每个索引都包含一个字符,我正在获取用户输入需要在该数组中搜索的字符。但是我不确定如何检查char cInput是否存在于数组的所有索引中。

char cLetters[5] = {'b', 'b', 'b', 'b', 'b'};
char cInput;
cout << "Enter a character to search for: ";
cin >> cInput;

我不应该这样做,对吗?
if(cInput == cLetters[0] && cInput == cLetters[1] && cInput == cLetters[2] 
&& cInput == cLetters[3] && cInput == cLetters[4])
          return true;

特别是当数组的大小为200时,我不会写200次那个条件语句。

有什么想法吗?


你的问题被标记为for循环。这个想法怎么样? - ApproachingDarknessFish
我今天一直脑子不清醒,非常抱歉。 - Mauri
4个回答

10

使用C++11中的算法库<algorithm>,使用std::all_of函数。

示例代码:

#include <algorithm>
#include <iostream>

int main() {
    char x[] = { 'b', 'b', 'b', 'b', 'b' };
    if(std::all_of(std::begin(x), std::end(x), [](char c) { return c == 'b'; })) {
        std::cout << "all are b!";
    }
}

@Cheersandhth.-Alf,实际上,C++11中添加了许多有用的算法和工具,但似乎人们都不知道。 std::to_stringstd::stoi 让我花了很长时间才弄明白。 - chris

2
我正在寻找一种使用布尔值来实现此操作的方法,我想到了以下代码:
auto is_true = std::bind(std::equal_to<bool>(), std::placeholders::_1, true);
return std::all_of(v.begin(), v.end(), is_true)

使用const char的话,代码会像这样:
auto is_b = std::bind(std::equal_to<char>(), std::placeholders::_1, 'b');
return std::all_of(v.begin(), v.end(), is_b)

0

如果输入字符在所有索引中都不存在,则它不会出现在其中任何一个索引中。循环遍历数组以查看。

for (int i=0; i<5; ++i){
    if (cInput != cLetters[i])
        return 0;
}
return 1;

0
另一种可能性是使用C++11的基于范围的for循环来简化代码:
for (auto ch : cLetters)
    if (ch != cInput)
        return false;
return true;

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接