Range access through non-member functions (begin, end)

Oh, this will be a short post. However, it’s a very important feature, that allows us for generic code.

Remember those containers with begin and end functions, that return iterators?

You can now use a generic method that receives the container as a parameter:

Why is this useful? Well, it works with different collection types, and even with C-style arrays (which obviously do not have any possibility to have these functions other than this).

Since we have begin and end now, we can also execute algorithms (such as std::accumulate) on these C-style arrays.

If we work with a third party container, which cannot be modified, but we can use other methods such as get, next, hasNext, we can use them in our begin/end free function so we can make them work with the std algorithms, with generic code that uses the begin/end free functions, or with ranged-based for loop.

You may also like...

Leave a Reply