2D Vector

2D Vector (Vector of Vectors) in C++

IntermediateTopic: STL Containers Programs
Back

C++ 2D Vector Program

This program helps you to learn the fundamental structure and syntax of C++ programming.

Try This Code
#include <iostream>
#include <vector>
using namespace std;

int main() {
    // Create 2D vector
    vector<vector<int>> matrix;
    
    // Initialize with 3 rows and 4 columns
    int rows = 3, cols = 4;
    matrix.resize(rows, vector<int>(cols));
    
    // Fill matrix
    int value = 1;
    for (int i = 0; i < rows; i++) {
        for (int j = 0; j < cols; j++) {
            matrix[i][j] = value++;
        }
    }
    
    // Display matrix
    cout << "2D Vector (Matrix):" << endl;
    for (int i = 0; i < rows; i++) {
        for (int j = 0; j < cols; j++) {
            cout << matrix[i][j] << "\t";
        }
        cout << endl;
    }
    
    // Another way: Initialize with values
    vector<vector<int>> matrix2 = {
        {1, 2, 3},
        {4, 5, 6},
        {7, 8, 9}
    };
    
    cout << "\nMatrix 2:" << endl;
    for (const auto& row : matrix2) {
        for (int num : row) {
            cout << num << " ";
        }
        cout << endl;
    }
    
    // Access elements
    cout << "\nElement at [1][2]: " << matrix2[1][2] << endl;
    cout << "Number of rows: " << matrix2.size() << endl;
    cout << "Number of columns in first row: " << matrix2[0].size() << endl;
    
    return 0;
}
Output
2D Vector (Matrix):
1	2	3	4	
5	6	7	8	
9	10	11	12	

Matrix 2:
1 2 3
4 5 6
7 8 9

Element at [1][2]: 6
Number of rows: 3
Number of columns in first row: 3

Understanding 2D Vector

A 2D vector is a vector of vectors. It's useful for representing matrices or tables where rows can have different sizes. Access elements using matrix[i][j]. resize() can be used to set dimensions. 2D vectors are more flexible than 2D arrays as they can dynamically resize. Each row is a separate vector, allowing jagged arrays.

Note: To write and run C++ programs, you need to set up the local environment on your computer. Refer to the complete article Setting up C++ Development Environment. If you do not want to set up the local environment on your computer, you can also use online IDE to write and run your C++ programs.

Table of Contents