Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ Find an int in an array

Tags:

c++

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?

like image 354
Cory Madden Avatar asked Sep 10 '25 17:09

Cory Madden


1 Answers

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.

like image 67
Kerrek SB Avatar answered Sep 13 '25 06:09

Kerrek SB