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()
?
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
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With