std::find on a legacy array

If you are using c++11, you can use:

int arr[N];
if (std::end(arr) == std::find(std::begin(arr), std::end(arr), value))
{
    // ...
}

For c++98, you can use:

int arr[N];
int *begin = arr;
int *end = begin + N;

if (end == std::find(begin, end, value))
{
    // ...
}

Your general idea is good. But ar[N] is not "reserved" for you. Dereferencing a not allocated variable will lead to undefined behavior. Your want to compare std::find result with ar + N, which does not involve dereferencing.


Is &ar[N] a valid value for checking the situation when nothing is found?

You can use ar+N instead of &ar[N], because ar +N is safe but &ar[N] falls into the region of undefined behavior (there is a long debate over that in fact).

Semantically speaking, the second argument is actually end of the range, so whatever you pass as second argument is returned when nothing is found in the range. In your case, ar + N is the second argument, which also indicates end of the range. So you can write this:

if ( std::find(ar, ar + N, value) != (ar + N) )
{ 
       //value found
}

Tags:

C++

Stl