InQusitive InQusitive - 18 days ago 5
C++ Question

find_if find a element not equal to something

#include<iostream>
#include<algorithm>

using namespace std;

int main()
{
int matrix[9] = { 1,0,0,0,1,0,0,0,5 };
bool status = true;

status = find_if(begin(matrix), end(matrix), [](auto const &value) ->bool
{ if (value != 0 && value != 1) return false; else return true; });

cout << status << endl;

}


I have a situation where I need to find if there is a value which is not equal to
1
and
0
present in the array. I thought of using
find_if
. But I am not able to make it work.

This code always
return true
. How do I make it right? The final status should be
false
if atleast one of the element in the array is non
1 and 0
.

Is the
find_if
method the correct one here?

Answer

find_if returns an iterator. In the case of the integer array it returns a pointer of type int * that is always converted to true because it is not a null pointer.

you should write instead

status = find_if(begin(matrix), end(matrix), [](auto const &value) ->bool
{ if (value != 0 && value != 1) return false; else return true; }) != end( matrix );

Another way is to use the standard algorithm std::any_of that indeed returns a Boolean value.