C ++ 11 Using "Range for Loop" (for each) for a dynamic array

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

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

      

Is it possible to do something like this when I have a pointer (int * b) and an array size (N)?

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

I would also prefer not to use std :: for_each, but that's an option.

+3


source to share


1 answer


Just use a wrapper container:

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

      

Using:



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

      

Demo .

With C ++ 1Z we can hopefully be able to use std::array_view

.

+6


source







All Articles