H.Das
H.Das

Reputation: 225

Confuse about Begin() method as param

I create a simple program

void method_2(int* arr, int* first, int * last){
// algorithm
}

void method_1(int arr[]){
method_2(arr, std::begin(arr), std::end(arr)); // No matching function for call begin()

}

Guys Why I'm getting "No matching function for call begin()" compiling error ? How can i solve this problem.

Upvotes: 0

Views: 42

Answers (1)

john
john

Reputation: 87959

This code is legal but deceptive

void method_1(int arr[]){

It looks as if arr is an array but it isn't. In C and C++ it is not possible to pass an array to a function. A pointer is used instead of an array. So the code above is exactly the same as

void method_1(int* arr){

That's the background. The problem is that although std::begin works for arrays it does not work for pointers, so

void method_1(int arr[]){
    method_2(arr, std::begin(arr), std::end(arr));

is not legal because arr is a pointer.

The root of the problem is that it is impossible to know from a pointer, pointing at an array of items, how many items it is pointing at.

How to fix it depends on what you are trying to do, there are many possibilities. The simple and standard one in C++ is to avoid arrays and pointers altogetther and use std::vector instead. One of the many advantages of std::vector is that you know how many items are in the vector at all times, so begin, end and size all work as expected.

Upvotes: 2

Related Questions