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.

3
  • ...a "old" normal for-loop? Commented Dec 6, 2014 at 18:44
  • 1
    Instead of a pointer and size as separate items, why not a std::vector? Commented Dec 6, 2014 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: stackoverflow.com/questions/28242073/… Commented Jan 30, 2015 at 20:48

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

1 Comment

How will the array_view be used?

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.