user972014
user972014

Reputation: 3856

C++11 Using "Range-based for loop" (for each) for dynamic array

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.

Upvotes: 3

Views: 878

Answers (1)

Columbo
Columbo

Reputation: 60999

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.

Upvotes: 6

Related Questions