So I've read other Stack posts about this, and they all suggest that I use find
. I'm attempting this, but it doesn't work for me.
bool findInArray(int number, int array[]){
// Finds if the number is in the array
bool exists = find(begin(array), end(array), number) != end(array);
return exists;
}
But I keep getting the following error:
error: no matching function for call to ‘begin(int*&)’
It's even the accepted answer here: How can I check if given int exists in array?
You need a template:
template <std::size_t N>
bool findInArray(int number, const int (&array)[N]) {
// Finds if the number is in the array
return std::find(std::begin(array), std::end(array), number) != std::end(array);
}
You also need to pass the array by lvalue, since you cannot pass arrays by prvalue in C++, and instead the array would decay to a pointer to its first element, thereby losing the size information.
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