I like to use std::algorithm
whenever I can on plain arrays. Now I have 2 doubts; suppose I want to use std::lower_bound
what happens if the value I provide as argument is not found?
int a[] = {1,2,3,4,5,6};
int* f = std::lower_bound(a,a+6,20);
The result I have when printing *f is 20.
The same happens if I use std::find
.
int a[] = {1,2,3,4,5,6};
int* f = std::find(a,a+6,20);
The result I have when printing *f is 20.
- Is it always the case that the return value is the original argument when this is not found?
- In terms of performance
std::lower_bound
performs better ofstd::find
since it implements a binary search algorithm. If the array is big say max 10 elements, could std::find perform better? Behind the scenes std::lower_bound calls std::advance and std::distance ..maybe I might save on these calls as well?
Thanks a lot
AFG
f
? Or*f
? If it'sf
, that's irrelevant, and unlikely. If it's*f
, you shouldn't be dereferencing f there. – Hillsif (f == a+6)
– Hillsend
iterator, which you're not allowed to dereference - but the particular flavour of undefined behaviour you got by dereferencing just happened to return the20
off the stack (but that's uninteresting because it's UB, unrelated objects need not be stored consecutively, padding exists, etc.) – Maulmain