I was writing a function to dump the contents of a 'matrix' in a vector-of-vectors to cout when I ran across conceptual difficulties. Here's the code of the working function:

#include <iostream>
#include <vector>
using namespace std;

void output_string_matrix(const vector<vector<string> >& matrix)
    vector<vector<string> >::const_iterator rows_itr;
    vector<string>::const_iterator cols_itr;

    for (rows_itr = matrix.begin(); rows_itr != matrix.end(); ++rows_itr)
        vector<string>::const_iterator cols_endpoint = rows_itr->end();
        for (cols_itr = rows_itr->begin(); cols_itr != cols_endpoint; ++cols_itr)
            cout << *cols_itr << "   ";
        cout << endl;

My question for local gurus: Why do the inner/"column" iterators need to be const_iterators? I can understand why the "rows" iterator needs to be const_iterator, but not why that's the case for the inner one.


Matrix is a const reference to a vector object right? This means it is illegal for you to modify it, including references to its elements which are vectors of vectors of strings. Needless to say, it is also illegal to modify the elements of the elements of the matrix, because, if this happens, then you've already modified the matrix. Iterators, which could also behave as pointers to the elements of a sequence they iterate over, can be used to modify the said elements. That's why the compiler is taking great pains to prevent this and it requires that const iterators be used in both the outer loop and the inner loop.

This article has been dead for over six months. Start a new discussion instead.