4

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?

Community
  • 1
  • 1
Cory Madden
  • 5,026
  • 24
  • 37

2 Answers2

8

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.

Kerrek SB
  • 464,522
  • 92
  • 875
  • 1,084
1

In case you do not know template and looking for an other answer to this question, use STL algorithms.

#include<iostream>
#include<algorithm>

bool findInArray(int number, int array[], int size_array){
  int* p   = std::find(array, array+size_array, number);
  if (p != array+size_array) {
    return 1;
  } else {
   return 0;
}

And from main, you can call :

findInArray(5, a, sizeof(a)/sizeof(a[0]));
Hemant Bhargava
  • 3,251
  • 4
  • 24
  • 45