Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 257
user972014 Avatar asked Dec 05 '25 17:12

user972014


1 Answers

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.

like image 167
Columbo Avatar answered Dec 08 '25 06:12

Columbo



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!