e42.uk Circle Device

 

Techie Stuff

Projects

Quick Reference

Will be moved to Quick Reference soon

Iterators in C++

Iterators in C++

The typical C++ for loop iterator:

std::vector<int> vec{0, 1, 2, 3, 4};
for (auto it = begin(vec); it != end(vec); ++it) {
    std::cout << *it << " ";
}

The above example is taken from Microsoft this pattern is repeated in many places and it does work... but is it correct? It is possible to perform the same work in C++17 like this:

std::vector<int> vec{0, 1, 2, 3, 4};
for (auto num : vec) {
    std::cout << num << " ";
}

But these examples are NOT equivalent, the detail can be found on the cppreference website. The problem with the first example is that the end() function is being called every time around the loop and creating a new iterator each time! It is relatively simple to modify the first code sample to make it equivalent:

std::vector<int> vec{0, 1, 2, 3, 4};
for (auto it = begin(vec), it_end = end(vec); it != it_end; ++it) {
    std::cout << *it << " ";
}

Now it and it_end are created only once and when they are equal the loop will terminate.

Quick Links: Techie Stuff | General | Personal | Quick Reference