Aleeee
Aleeee

Reputation: 2023

error: no matching function for call to 'begin(int*&)' c++

#include <iostream>
#include <iterator>
using namespace std;
void print(int ia[])
{
    int *p = begin(ia);
    while(p != end(ia))
        cout<<*p++<<'\t';
}

int main()
{
    int ia[] = {1,2,3,4},i;
    print(ia);

    return 0;
}

P pointer to the first element in ia. why it said"error: no matching function for call to 'begin(int*&)' c++" thanks!:)

Upvotes: 16

Views: 31774

Answers (3)

Leonid Volnitsky
Leonid Volnitsky

Reputation: 9144

As others pointed out, your array is decaying to a pointer. Decaying is historical artifact from C. To do what you want, pass array as reference and deduce array size:

template<size_t X>
void print(int (&ia)[X])
{
    int *p = begin(ia);
    while(p != end(ia))
        cout<<*p++<<'\t';
}

print(ia);

Upvotes: 8

P0W
P0W

Reputation: 47824

You are using the begin and end free functions on a pointer, that's not allowed.

You can do something similar with C++11's intializer_list

//g++ -std=c++0x test.cpp -o test
#include <iostream>
#include <iterator>
using namespace std;
void print(initializer_list<int> ia)
{
    auto p = begin(ia);
    while(p != end(ia))
        cout<<*p++<<'\t';
}

int main()
{
    print({1,2,3,4});   
    return 0;
}

Upvotes: 9

Oliver Charlesworth
Oliver Charlesworth

Reputation: 272657

Because inside print(), the variable ia is a pointer, not an array. It doesn't make sense to call begin() on a pointer.

Upvotes: 16

Related Questions