Like many people these days I have been trying the different features that C++11 brings. One of my favorites is the \"range-based for loops\".
I understand that:
I write my answer because some people might be more happy with simple real life example without STL includes.
I have my own plain only data array implementation for some reason, and I wanted to use the range based for loop. Here is my solution:
template
class PodArray {
public:
class iterator {
public:
iterator(DataType * ptr): ptr(ptr){}
iterator operator++() { ++ptr; return *this; }
bool operator!=(const iterator & other) const { return ptr != other.ptr; }
const DataType& operator*() const { return *ptr; }
private:
DataType* ptr;
};
private:
unsigned len;
DataType *val;
public:
iterator begin() const { return iterator(val); }
iterator end() const { return iterator(val + len); }
// rest of the container definition not related to the question ...
};
Then the usage example:
PodArray array;
// fill up array in some way
for(auto& c : array)
printf("char: %c\n", c);