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.
1#include <iostream>2#include <vector>3using namespace std;45int main() {6 // Create 2D vector7 vector<vector<int>> matrix;89 // Initialize with 3 rows and 4 columns10 int rows = 3, cols = 4;11 matrix.resize(rows, vector<int>(cols));1213 // Fill matrix14 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 }2021 // Display matrix22 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 }2930 // Another way: Initialize with values31 vector<vector<int>> matrix2 = {32 {1, 2, 3},33 {4, 5, 6},34 {7, 8, 9}35 };3637 cout << "\nMatrix 2:" << endl;38 for (const auto& row : matrix2) {39 for (int num : row) {40 cout << num << " ";41 }42 cout << endl;43 }4445 // Access elements46 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;4950 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
resize to 3 rows of vector<int>(4).
- 2
Fill with 1 to 12 using nested loops.
- 3
Print with tabs between values.
- 4
Create matrix2 with nested braces.
- 5
Print it with range-based loops.
- 6
Print matrix2[1][2], the row count, and the first row's length.
Dry run: 2D Vector
matrix after filling:
- 1.row 0: 1 2 3 4
- 2.row 1: 5 6 7 8
- 3.row 2: 9 10 11 12
- 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 → 6Edge 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:
Declaration:
vector<vector<int>> matrix;
What happens here:
Creating 2D Vector
Empty 2D Vector:
vector<vector<int>> matrix;
Setting Dimensions:
matrix.resize(rows, vector<int>(cols));
What happens here:
Accessing Elements
Element Access:
matrix[i][j] // Element at row i, column j
What happens here:
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:
Initializing with Values
Initialization:
vector<vector<int>> matrix2 = {
{1, 2, 3},
{4, 5, 6},
{7, 8, 9}
};
What happens here:
Different Row Sizes
Jagged Array:
vector<vector<int>> jagged = {
{1, 2},
{3, 4, 5},
{6, 7, 8, 9}
};
What happens here:
When to Use 2D Vectors
Good fits:
Example Scenarios:
Important Considerations
Memory Layout:
Performance:
Size Information:
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.