Reputation: 53
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?
Upvotes: 3
Views: 1830
Reputation: 1665
I'm looking for a way to do this with bools and came up with this:
auto is_true = std::bind(std::equal_to<bool>(), std::placeholders::_1, true);
return std::all_of(v.begin(), v.end(), is_true)
With a const char it would look like so:
auto is_b = std::bind(std::equal_to<char>(), std::placeholders::_1, 'b');
return std::all_of(v.begin(), v.end(), is_b)
Upvotes: 2
Reputation: 490088
Another possibility would be to use a C++11 range-based for loop to simplify the code a little:
for (auto ch : cLetters)
if (ch != cInput)
return false;
return true;
Upvotes: 0
Reputation: 33
The input char is not present in all indices if it is absent in either one of those. Loop through the array to see that
for (int i=0; i<5; ++i){
if (cInput != cLetters[i])
return 0;
}
return 1;
Upvotes: 0
Reputation: 21317
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!";
}
}
Upvotes: 10