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

This program teaches you how to use 2D Vectors (Vector of Vectors) in C++. A 2D vector is a vector where each element is itself a vector, creating a two-dimensional structure. It's useful for representing matrices, tables, or grids where rows can have different sizes.

---

1. What This Program Does

The program demonstrates 2D vector operations:

Creating 2D vector (vector of vectors)
Setting dimensions using resize()
Accessing elements using matrix[i][j]
Initializing with values
Working with different row sizes

2D vectors provide flexible, dynamic two-dimensional data structures.

---

2. Header Files Used

1.#include <iostream>
Provides cout and cin for input/output operations.
2.#include <vector>
Provides vector container class.

---

3. Understanding 2D Vectors

2D Vector Concept

:

Vector where each element is a vector
Creates two-dimensional structure
Each row is a separate vector
Can have different row sizes (jagged arrays)

Declaration

:

vector<vector<int>> matrix;

How it works

:

Outer vector contains rows
Each row is a vector of elements
Access: matrix[row][column]

---

4. Creating 2D Vector

Empty 2D Vector

:

vector<vector<int>> matrix;

Setting Dimensions

:

matrix.resize(rows, vector<int>(cols));

How it works

:

resize() sets number of rows
Each row initialized with cols columns
Creates rows × cols matrix
All elements default-initialized

---

5. Accessing Elements

Element Access

:

matrix[i][j] // Element at row i, column j

How it works

:

First index [i]: row number
Second index [j]: column number
Like 2D arrays but dynamic
Can access and modify

Example

:

matrix[1][2] = 6; // Set element at row 1, column 2

---

6. Filling 2D Vector

Nested Loops

:

for (int i = 0; i < rows; i++) {

for (int j = 0; j < cols; j++) {

matrix[i][j] = value++;

}

}

How it works

:

Outer loop: iterate rows
Inner loop: iterate columns
Fill each element sequentially
Can fill with any pattern

---

7. Initializing with Values

Initialization

:

vector<vector<int>> matrix2 = {

{1, 2, 3},

{4, 5, 6},

{7, 8, 9}

};

How it works

:

Initialize with nested braces
Each inner brace is a row
Rows can have different sizes
Creates jagged array if needed

---

8. Different Row Sizes

Jagged Array

:

vector<vector<int>> jagged = {

{1, 2},

{3, 4, 5},

{6, 7, 8, 9}

};

How it works

:

Each row can have different size
More flexible than 2D arrays
Useful for irregular data
Access: jagged[i][j] (j must be < row size)

---

9. When to Use 2D Vectors

Best For

:

Matrices and grids
Tables with variable row sizes
Dynamic 2D data structures
When size unknown at compile time
Jagged arrays

Example Scenarios

:

Matrix operations
Game boards
Data tables
Graph representations
Image processing

---

10. Important Considerations

Memory Layout

:

Rows stored separately
Not contiguous like 2D arrays
Each row can be in different memory location
Slightly less cache-friendly

Performance

:

Access: O(1) like arrays
Resizing: can be expensive
More flexible than 2D arrays
Slight overhead vs 2D arrays

Size Information

:

matrix.size(): number of rows
matrix[i].size(): columns in row i
Can have different row sizes

---

11. return 0;

This ends the program successfully.

---

Summary

2D vector: vector of vectors, creates two-dimensional structure.
Access elements: matrix[i][j] (row i, column j).
resize() sets dimensions: matrix.resize(rows, vector<int>(cols)).
More flexible than 2D arrays - can resize and have different row sizes.
Each row is separate vector, allowing jagged arrays.
Understanding 2D vectors enables dynamic matrices and tables.
Essential for matrices, grids, and two-dimensional data structures.

This program is fundamental for learning multi-dimensional data structures, understanding dynamic matrices, and preparing for advanced algorithms and data processing in C++ programs.

Let us now understand every line and the components of the above program.

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.

Practical Learning Notes for 2D Vector

This C++ program is part of the "STL Containers Programs" topic and is designed to help you build real problem-solving confidence, not just memorize syntax. Start by understanding the goal of the program in plain language, then trace the logic line by line with a custom input of your own. Once you can predict the output before running the code, your understanding becomes much stronger.

A reliable practice pattern is to run the original version first, then modify only one condition or variable at a time. Observe how that single change affects control flow and output. This deliberate style helps you understand loops, conditions, and data movement much faster than copying full solutions repeatedly.

For interview preparation, explain this solution in three layers: the high-level approach, the step-by-step execution, and the time-space tradeoff. If you can teach these three layers clearly, you are ready to solve close variations of this problem under time pressure.

Table of Contents