iterator.cc 1.3 KB
/*
 * A short intro to iterators using vector as an example.
 * An iterator is a generic way of accessing and stepping through a
 * container. The iterators is modelled after normal pointers
 */
#include <iostream>
#include <vector>
using namespace std;


int main()
{
    // create a vector containing 10 int values
    vector<int> v(10);

    // range-based for-loop. For each element i in the vector v
    for ( int i: v )
    {
        // will only modify a copy of the element
        cout << ++i << endl;
    }

    // make i a reference to an element.
    for ( int & i: v )
    {
        cout << ++i << endl;
    }
    
    // normal index-based for loop.
    for ( /*vector<int>::size_type*/ size_t i {}; i < 10; ++i )
    {
//        cout << v[i] << endl;
        cout << v.at(i) << endl;
    }
    
    // iterator-based loop. begin(v) gives an iterator that refererences
    // the first element of v, end(v) gives an iterator to past the end.
    for ( auto it { begin(v) }; it != end(v); ++it )
    {
        int & i {*it};
        cout << ++i << endl;
    }

    // Both of these are wrong (and for vector eqivalent)
    cout << *end(v) << endl;
    cout << v[10] << endl;

    // iterators are used hevily in the standard library
    // Here we are inserting the value 5 at index 2.
    v.insert(begin(v)+2, 5);
}