Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

std::find on a legacy array

Tags:

c++

stl

How can i conduct std::find on a legacy array without making a new std::vector/std::array from an existing legacy array?

for example:

int ar[N];

if ( std::find(ar, ar + N, value) != &ar[N] ){ /**/ }

Is &ar[N] a valid value for checking the situation when nothing is found? Can I be sure i'm doing right using &ar[N] like an analog of std::vector::end() ?

like image 989
fogbit Avatar asked Dec 18 '12 13:12

fogbit


3 Answers

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))
{
    // ...
}
like image 79
utnapistim Avatar answered Nov 16 '22 18:11

utnapistim


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.

like image 37
tomahh Avatar answered Nov 16 '22 19:11

tomahh


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
}
like image 3
Nawaz Avatar answered Nov 16 '22 19:11

Nawaz