3

If I have a static array, I can do something like that:

int a[] = {1, 2, 3};
for (const auto x: a) {printf("%d\n", x);} 

Can I do something similar when I have a pointer (int* b) and array size (N)?

I'd rather avoid defining my own begin() and end() functions.

I'd also prefer not using std::for_each, but it's an option.

user972014
  • 3,296
  • 6
  • 49
  • 89
  • ...a "old" normal for-loop? – deviantfan Dec 06 '14 at 18:44
  • 1
    Instead of a pointer and size as separate items, why not a `std::vector`? – Jerry Coffin Dec 06 '14 at 18:47
  • No, because of a quirky detail about namespaces, and even if possible the loop wouldn't know the size of the dynamic array. Related: http://stackoverflow.com/questions/28242073/viewing-a-raw-pointer-as-a-range-in-range-based-for-loop – alfC Jan 30 '15 at 20:48

1 Answers1

6

Just use a container-like wrapper:

template <typename T>
struct Wrapper
{
    T* ptr;
    std::size_t length;
};

template <typename T>
Wrapper<T> make_wrapper(T* ptr, std::size_t len) {return {ptr, len};}

template <typename T>
T* begin(Wrapper<T> w) {return w.ptr;}

template <typename T>
T* end(Wrapper<T> w) {return begin(w) + w.length;}

Usage:

for (auto i : make_wrapper(a, sizeof a / sizeof *a))
    std::cout << i << ", ";**

Demo.

With C++1Z we will hopefully be able to use std::array_view instead.

Columbo
  • 60,038
  • 8
  • 155
  • 203