检查是否存在于数组中的所有指标值
问题描述:
所以我有一个字符数组(大小5),包含每个索引字符,我得到一个字符的用户输入数组中搜索。但我不知道如何检查字符cInput
是阵列的所有指标present。
So i have an array (size 5) of characters, each index containing a character, and i'm getting user input of a character to search for in the array. But i'm not sure how to check if char cInput
is present in all indexes of the array.
char cLetters[5] = {'b', 'b', 'b', 'b', 'b'};
char cInput;
cout << "Enter a character to search for: ";
cin >> cInput;
我不应该这样做对吗?
I shouldn't have to do this right?
if(cInput == cLetters[0] && cInput == cLetters[1] && cInput == cLetters[2]
&& cInput == cLetters[3] && cInput == cLetters[4])
return true;
特别是如果数组的大小是200,我不会写条件的200倍。
Especially if the size of the array was 200, i wouldn't write that condition 200 times.
任何想法?
答
使用在C ++ 11的算法&LT;算法&GT;
, 的std :: all_of
。
Use the C++11 algorithm in <algorithm>
, std::all_of
.
举例code:
#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!";
}
}