Mau*_*uri 3 c++ arrays loops for-loop
所以我有一个数组(大小为5)的字符,每个索引包含一个字符,我得到一个字符的用户输入在数组中搜索.但我不知道如何检查char cInput数组的所有索引中是否存在.
char cLetters[5] = {'b', 'b', 'b', 'b', 'b'};
char cInput;
cout << "Enter a character to search for: ";
cin >> cInput;
Run Code Online (Sandbox Code Playgroud)
我不应该这样做吗?
if(cInput == cLetters[0] && cInput == cLetters[1] && cInput == cLetters[2]
&& cInput == cLetters[3] && cInput == cLetters[4])
return true;
Run Code Online (Sandbox Code Playgroud)
特别是如果阵列的大小是200,我不会写那个条件200次.
有任何想法吗?
Rap*_*ptz 10
在<algorithm>,使用C++ 11算法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!";
}
}
Run Code Online (Sandbox Code Playgroud)