Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why can't I use std::begin/std::end with int(*p)[3] while I can with int(&p)[3]?

Tags:

c++

This works:

void foo(int (&a)[3]) {
    auto ibegin = begin(a);
    auto ebegin = end(a);
}

While this doesn't:

void foo(int (*a)[3]) {
    auto ibegin = begin(a);
    auto ebegin = end(a);
}

I consider int (&a)[3] and int (*a)[3] have the same meaning!

like image 713
Rick Avatar asked Nov 29 '22 06:11

Rick


1 Answers

Your code is analogous to:

void foo(vector<int>& a) {
    auto ibegin = begin(a);
    auto ebegin = end(a);
}

void foo(vector<int>* a) {
    auto ibegin = begin(a);
    auto ebegin = end(a);
}

The first one works and the second one doesn't for the same reason as it works on int (&a)[3] and doesn't on int (*a)[3]. When you're using pointers to collections instead of references, you need to dereference them when you pass them to the standard library's begin/end.

void foo(vector<int>* a) {
    auto ibegin = begin(*a);
    auto ebegin = end(*a);
}

void foo(int (*a)[3]) {
    auto ibegin = begin(*a);
    auto ebegin = end(*a);
}
like image 98
zneak Avatar answered Nov 30 '22 21:11

zneak