Course offer · HLD · LLD · System Design at ₹799 until 30 Nov (not interview packs)

2D Vector in C++

Build a 2D vector in C++: size it with resize, fill it with nested loops, initialize with nested braces, read matrix[i][j], and handle rows of different lengths.

IntermediateSTL Containers ProgramsExample 3 of 10
2d-vector.cpp
1#include <iostream>
2#include <vector>
3using namespace std;
4
5int main() {
6 // Create 2D vector
7 vector<vector<int>> matrix;
8
9 // Initialize with 3 rows and 4 columns
10 int rows = 3, cols = 4;
11 matrix.resize(rows, vector<int>(cols));
12
13 // Fill matrix
14 int value = 1;
15 for (int i = 0; i < rows; i++) {
16 for (int j = 0; j < cols; j++) {
17 matrix[i][j] = value++;
18 }
19 }
20
21 // Display matrix
22 cout << "2D Vector (Matrix):" << endl;
23 for (int i = 0; i < rows; i++) {
24 for (int j = 0; j < cols; j++) {
25 cout << matrix[i][j] << "\t";
26 }
27 cout << endl;
28 }
29
30 // Another way: Initialize with values
31 vector<vector<int>> matrix2 = {
32 {1, 2, 3},
33 {4, 5, 6},
34 {7, 8, 9}
35 };
36
37 cout << "\nMatrix 2:" << endl;
38 for (const auto& row : matrix2) {
39 for (int num : row) {
40 cout << num << " ";
41 }
42 cout << endl;
43 }
44
45 // Access elements
46 cout << "\nElement at [1][2]: " << matrix2[1][2] << endl;
47 cout << "Number of rows: " << matrix2.size() << endl;
48 cout << "Number of columns in first row: " << matrix2[0].size() << endl;
49
50 return 0;
51}

Sample Output

1	2	3	4	

Row 0; each value is followed by a tab.

Element at [1][2]: 6

Row {4, 5, 6}, index 2.

In this one

  • How a vector of vectors models a grid
  • How resize creates rows and columns at once
  • Why the loop uses const auto& for rows
  • How to get row and column counts

How it works

  1. 1

    resize to 3 rows of vector<int>(4).

  2. 2

    Fill with 1 to 12 using nested loops.

  3. 3

    Print with tabs between values.

  4. 4

    Create matrix2 with nested braces.

  5. 5

    Print it with range-based loops.

  6. 6

    Print matrix2[1][2], the row count, and the first row's length.

Dry run: 2D Vector

matrix after filling:

  1. 1.row 0: 1 2 3 4
  2. 2.row 1: 5 6 7 8
  3. 3.row 2: 9 10 11 12
  4. 4.matrix2[1][2]: row 1 is {4, 5, 6}, index 2 → 6
matrix after filling:
row 0: 1  2  3  4
row 1: 5  6  7  8
row 2: 9 10 11 12
matrix2[1][2]: row 1 is {4, 5, 6}, index 2 → 6

Edge cases

Empty grid

Ask for matrix[0].size() before resize.

There is no row 0, so this is undefined behavior. Check matrix.empty() first.

Jagged rows

Add a row with matrix2.push_back({1, 2});

The grid now has rows of length 3 and 2. Loop with row.size(), not a fixed column count.

What's going on

A 2D vector is a vector whose elements are themselves vectors. Each inner vector is one row, so matrix[i][j] reads row i, column j.

vector<vector<int>> matrix; starts with no rows at all. matrix.resize(rows, vector<int>(cols)); makes 3 rows, each a copy of a 4-element vector of zeros. That one line is the usual way to size a grid.

The nested loops fill the grid row by row with an increasing counter, giving 1 to 12. The display loop prints each value followed by a tab (\t) so the columns line up, and endl after each row.

matrix2 is built directly with nested braces, three rows of three. The range-based loop for (const auto& row : matrix2) takes each row by const reference, which avoids copying the whole inner vector on every pass. The inner loop then prints that row's numbers.

matrix2[1][2] is row 1, column 2 (counting from 0), which is 6. matrix2.size() is the number of rows and matrix2[0].size() is the length of the first row.

Rows do not have to be the same length. You could push_back a 5-element vector onto matrix2 and it would be a jagged grid. That flexibility is why the code asks for matrix2[0].size() specifically: each row knows its own length.

One cost to know about: each row is a separate heap allocation, so a big grid is not one contiguous block. For heavy numeric work, people often use one flat vector<int> of size rows × cols and index it as v[i * cols + j].

The headers come first. <iostream> is there because it provides cout and cin for input/output operations. <vector> is there because it provides vector container class. Leave one out and the compiler stops at the first name it does not recognize.

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;

What happens here:

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

Creating 2D Vector

Empty 2D Vector:

vector<vector<int>> matrix;

Setting Dimensions:

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

What happens here:

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

Accessing Elements

Element Access:

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

What happens here:

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

Filling 2D Vector

Nested Loops:

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

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

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

}

}

What happens here:

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

Initializing with Values

Initialization:

vector<vector<int>> matrix2 = {

{1, 2, 3},

{4, 5, 6},

{7, 8, 9}

};

What happens here:

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

Different Row Sizes

Jagged Array:

vector<vector<int>> jagged = {

{1, 2},

{3, 4, 5},

{6, 7, 8, 9}

};

What happens here:

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

When to Use 2D Vectors

Good fits:

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

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

return 0;

return 0; closes main and tells the operating system the program finished without an error.

Quiz

Tap an option. The answer stays hidden until you pick.

Question 1

Given matrix2 = {{1,2,3},{4,5,6},{7,8,9}}, what is matrix2[2][0]?

Pick an answer to check it.

Question 2

What does matrix2.size() return?

Pick an answer to check it.

Questions people ask

How do I make an n × m grid filled with -1?

vector<vector<int>> g(n, vector<int>(m, -1));

Is a 2D vector slower than a 2D array?

A little, because rows are separate allocations. For most programs the difference does not matter.

How do I pass it to a function?

By reference: void show(const vector<vector<int>>& m) avoids copying every row.