#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!:)
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);
Because inside print()
, the variable ia
is a pointer, not an array. It doesn't make sense to call begin()
on a pointer.
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;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With