Enhanced FOR loops in C++

In C++11, if your compiler supports it, yes it is. It’s called range-based for.

std::vector<int> v;

// fill vector

for (const int& i : v) { std::cout << i << "\n"; }

It works for C style arrays and any type that has functions begin() and end() that return iterators. Example:

class test {
    int* array;
    size_t size;
public:
    test(size_t n) : array(new int[n]), size(n)
    {
        for (int i = 0; i < n; i++) { array[i] = i; }
    }
    ~test() { delete [] array; }
    int* begin() { return array; }
    int* end() { return array + size; }
};

int main()
{
    test T(10);
    for (auto& i : T) {
        std::cout << i;   // prints 0123456789
    }
}

Leave a Comment