mardi 26 février 2019

Implement is_array in c++

It's easy to find an item in a vector and we know how. It's also possible to find an item in an array if we know the length of the array. But starting from c++11 with the announcement of std:: end(), it looks like we can get the size of the array by calling its pointer, right?

So this code works:

int arr[] = {1,2,3,4,5};
int needle = 3;

std::find(begin(arr), end(arr), needle);
int* result = find(begin(arr), end(arr), needle);
bool exists = result!=end(arr);

However, if this converted to a function:

bool in_array(int arr[], int needle){
    int* result = std::find(begin(arr), end(arr), needle);
    return result!=end(arr);
}

Will not compile:

error: no matching function for call to ‘begin(int*&)’ int* result = std::find( std::begin(arr), std::end(arr), needle);

The goal is to make a working function to send any type of array to it, just like in_array of Php:

template <typename T>
T in_array(T arr[],T needle){
    T* result = std::find(begin(arr), end(arr), needle);
    return result!=end(arr);
}

Why does this code not work? Does C++ compiler store some kind of a local variable to determine the end of arr?

Aucun commentaire:

Enregistrer un commentaire