Iterators vs. auto in C++

The range-based for loop that is available since the C++ 11 standard, is a wonderful mean of making the code compact and clean. This post is totally dedicated to a single go: to show the difference between iterating using STL iterators and using for ranges.

Here’s a simple code that creates a vector of integers and prints them all. The first program uses the old approach.

#include <iostream>
#include <vector>

int main() {
    std::vector<int> data {10, 20, 30, 40};

    for (std::vector<int>::iterator i = data.begin();
        i != data.end(); i++) {
        std::cout << *i << "\n";
    }
}

You can clearly see how heavy is the code. Of course, you can simplify it a bit with the using namespace std instruction or creating the typedef for the vector type. The latter is actually a good idea as that helps to avoid constructing the same data type twice.

Nevertheless, switch to modern C++ and use the ranged-based for loops. This is how the program can be transformed:

#include <iostream>
#include <vector>

int main() {
    std::vector<int> data {10, 20, 30, 40};

    for (auto x : data) {
        std::cout << x << "\n";
    }
}

Two things to note here.

First, the absence of any manual work with an iterator (and there’s no explicit iterator itself).

Second, the auto keyword gives the compiler ability to deduce the correct type for the x variable. You—as a developer—do not need to think about that at the point of entering the loop. You already created your data and its type.

Also, notice the way vectors can be initialised in modern C++:

std::vector<int> data {10, 20, 30, 40};

Leave a Reply