how to iterate 2d vector in c++ code example

Example 1: initializing 2d vector

vector<vector<int> > vec( n , vector<int> (m, 0));

Example 2: how to iterate over 2d vector c++

#include<iostream>
#include<vector>
using namespace std;
/*
Iterate over vector of vectors and for each of the 
nested vector print its contents
*/
template <typename T>
void print_2d_vector(const vector< vector<T> > & matrix)
{
    for(auto row_obj : matrix)
    {
        for (auto elem: row_obj)
        {
            cout<<elem<<", ";
        }
        cout<<endl;
    }
    cout<<endl;
}

Tags:

Cpp Example