Search code examples
c++matrixiteratorstdstdvector

How to iterate through a vector of vector in C++?


I would like to know if it is possible to access the elements of std::vector<std::vector<int>> via iterators: I cannot understand why this won't compile:

#include<vector> 
#include<iostream> 

std::vector<std::vector<int>> vec {{1,2},{3,4}} ; 

// to access the single vector 
auto it = vec.begin() ; 

// to access the element of the vector 
auto iit = it.begin() ; 

Here the error I get:

prova.cpp: In function ‘int main()’:
prova.cpp:10:15: error: ‘class __gnu_cxx::__normal_iterator<std::vector<int>*, std::vector<std::vector<int> > >’ has no member named ‘begin’
   10 | auto iit = it.begin() ;

Solution

  • auto iit = it.begin();
    

    doesn't compile because it is an iterator, not a vector. You should use the overloaded value-of operator to get the vector pointed to by it.

    auto iit = (*it).begin();
    

    Then you can use the iterators as normal. You can also use range-based for-loops:

    for(auto &row : vec) {
        for(auto &col : row) {
            // do things
        }
    }