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

check if value exists in all indexes of array

本文关键字:是否 存在 索引 数组 检查      更新时间:2023-10-16

所以我有一个字符数组(大小为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次这个条件。

有什么想法吗?

<algorithm>std::all_of中使用C++11算法。

示例代码:

#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!";
    }
}

我正在寻找一种用bools实现这一点的方法,并想出了这个:

auto is_true = std::bind(std::equal_to<bool>(), std::placeholders::_1, true);
return std::all_of(v.begin(), v.end(), is_true)

如果使用const字符,它看起来是这样的:

auto is_b = std::bind(std::equal_to<char>(), std::placeholders::_1, 'b');
return std::all_of(v.begin(), v.end(), is_b)

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

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

另一种可能性是使用基于C++11范围的for循环来稍微简化代码:

for (auto ch : cLetters)
    if (ch != cInput)
        return false;
return true;