Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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!:)

like image 449
Aleeee Avatar asked Jul 25 '13 02:07

Aleeee


3 Answers

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);
like image 83
Leonid Volnitsky Avatar answered Nov 11 '22 21:11

Leonid Volnitsky


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

like image 27
Oliver Charlesworth Avatar answered Nov 11 '22 20:11

Oliver Charlesworth


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;
}
like image 8
P0W Avatar answered Nov 11 '22 21:11

P0W