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

  • A+
Category:Languages

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!


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); } 

Comment

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: