C ++ Find int in an array
So, I've read other Stack posts about this and they all suggest using find
. I am trying to do 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*&)’
This is even the accepted answer here: How do I check if a given int exists in an array?
+3
source to share
2 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 an lvalue array as you cannot pass arrays by prvalue in C ++ and instead the array will decay to a pointer to its first element, thereby losing size information.
+8
source to share
If you don't know the pattern and are looking for another 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 the main one you can call:
findInArray(5, a, sizeof(a)/sizeof(a[0]));
+1
source to share