Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.3k views
in Technique[技术] by (71.8m points)

c++ - check if value exists in all indexes of array

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;

Especially if the size of the array was 200, i wouldn't write that condition 200 times.

Any ideas?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Use the C++11 algorithm in <algorithm>, std::all_of.

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...