Reputation: 3856
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
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