cpp / intermediate
Snippet
Custom Range-based Iteration
By implementing begin() and end() methods that return pointers (or iterators), you enable your custom classes to be used with C++ range-based for loops.
snippet.cpp
cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
#include <iostream>class NumberBox {int data[3] = {10, 20, 30};public:int* begin() { return &data[0]; }int* end() { return &data[3]; }};int main() {NumberBox box;for (int val : box) {std::cout << val << " ";}return 0;}
Breakdown
1
int* begin() { return &data[0]; }
Returns a pointer to the first element of the internal array.
2
for (int val : box)
The compiler uses the begin() and end() methods to iterate through the object.