Remi.b Remi.b - 1 year ago 83
C++ Question

Differences between looping with an integer or an iterator in C++

As a C++ newbie, I am just discovering iterators. I realize that one can use either an

or an
for loop through any container. Consider for example

#include <iostream>
#include <vector>

int main()
std::vector<int> v;

std::cout << "i is an int: ";
for (int i = 0; i<v.size();i++)
std::cout << v[i] << " ";
std::cout << std::endl;

std::cout << "i is an iterator: ";
for (std::vector<int>::iterator i = v.begin(); i!=v.end();i++)
std::cout << *i << " ";
std::cout << std::endl;

which outputs

i is an int: 1 4 8
i is an iterator: 1 4 8

Generally speaking,

  • is there any advantage of using one or the other method?

  • Is one faster than the other one?

  • When should I use an
    and when should I use an

Answer Source

The primary reason for iterators is to provide generality. In particular, a generic algorithm can traverse a variety of containers using an iterator whose type is passed as a template parameter:

template <class InIt>
void print(InIt b, InIt e) { 
    while (b != e) {
        std:cout << *b << ' ';

In this case you get an advantage from the iterator because you can print a list or map (to give only a couple of example) just as well as a vector.

If you're working directly with a container of known type, that's not really an issue though. If you really just want to print out the items in a vector, using an integer to index into it works perfectly fine. Using an index instead of an iterator can have an advantage if you're modifying the collection instead of just reading its contents. For example, if you might do a push_back onto the vector inside the loop, an integer index would remain valid, but an iterator would potentially be invalidated1.

For the case you've shown, however, you probably want to consider a range-based for loop to avoid using either an index or an iterator:

for (auto i : v)
    std::cout << i << ' ';

1. Note that although this is true of standard iterators, it is possible to create an iterator type that remains valid in such a situation, if you really need/want it. For example:

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download