If you have learned about dynamic arrays, you already know how useful they are for storing data that can change in size. "2D Vectors in C++" work in a similar way, but they are safer and easier to use.
A 2D vector is simply a vector that stores other vectors. This helps us represent data in rows and columns, just like a matrix. This makes it a good choice for homework, lab work, and exams.
In this article, we will first understand the basics of 2D vectors. Then we will go through simple examples for declaring, printing, sorting, and changing a 2D vector, so the concept becomes clear and easy to remember.
TL;DR: 2D Vector In C++
| Aspect | Summary |
|---|---|
| Concept | A 2D vector in C++ is a vector of vectors, where each inner vector represents a row. Unlike a 2D array, its size can change, which makes it suitable for problems where you don't know the size in advance. |
| Memory Behavior | Each row is stored as its own separate block of memory. The elements inside one row sit next to each other, but the rows themselves are not joined together like they are in a 2D array. |
| Exam Usage | 2D vectors are commonly used when a problem mentions a user-defined size, dynamic input, a grid, or matrix-like operations. |
| Common Pitfalls | Students often confuse row size with column size and assume all rows are equal. Wrong loop limits and using a vector before giving it a size cause most of the crashes. |
| Best Practice | Always give the 2D vector its size before accessing elements, and use zap[i].size() for the inner loop. |
What Is A Vector In C++ Programming Language?
A C++ vector is a dynamic container provided by the Standard Template Library (STL) that stores its elements in a continuous block of memory. Unlike arrays, vectors resize automatically when elements are added or removed, which helps students avoid memory management errors.
// Example Of Single Vector Declaration (Needs #include <vector>)
vector<int> v1 = {1, 2, 3, 4}; // Initializer List Method
vector<int> v2{1, 2, 3, 4}; // Uniform Initialization Method
vector<int> v3(10, 5); // Ten Elements, Each One Is 5
From a learning and exam point of view, vectors are preferred because they are safer, flexible, and widely used in real-world C++ applications. Understanding vectors also builds a strong foundation for data structures and competitive programming.
What Is A 2D Vector In C++? Read Below
A two-dimensional vector is the extended version of a single-dimensional vector. Here, the vector concept is used twice. The outer vector holds the rows, and every row is an inner vector that holds the column values. It is the same idea as the 2D array data structure in other programming languages.
// Example Of Normal 2D Vector Declaration Process
vector<vector<int>> v; // An Empty 2D Vector: No Rows, No Columns Yet
The difference is that the two-dimensional vector is dynamic. That is the reason it is more convenient to use. Whenever elements are inserted into or deleted from the 2D vector, it resizes itself automatically.
One small thing about the syntax: you may see older code written as vector<vector<int> > with a space between the two closing brackets. That space was needed before C++11. Any compiler you use for class today accepts vector<vector<int>> without the space.
Why Students Get Confused With 2D Vectors In C++?
- Students often do not clearly understand that a 2D vector is actually a vector of vectors, not a single block of memory like a 2D array.
- Many beginners mix up row size and column size, which leads to wrong loop conditions and runtime errors.
- Students assume all rows must have the same number of columns, which is not always true in a 2D vector.
- The syntax
vector<vector<int>>looks complex at first, especially for students who are new to the STL. - Learners struggle with dynamic resizing because they are used to the fixed-size arrays they see in textbooks.
Comparison Table Between The 2D Vector And 2D Array
We have seen many times that students confuse a 2D array and a 2D vector in exams. This confusion happens simply because they are not aware of the differences between the two.
To help you with assignments and homework, here is a comparison table between a 2D vector and a 2D array.
| Criteria | 2D Array | 2D Vector |
|---|---|---|
| Size | Fixed when you write the code | Can be decided while the program runs |
| Memory | One continuous block | Each row is a separate block |
| Resizing | Impossible | Possible, row by row |
| Rows Of Different Length | Not possible | Possible (jagged vector) |
| Safety | Lower, no bounds checking | Higher, at() checks the index for you |
| Knows Its Own Size | No, you track it yourself | Yes, through size() |
| Exam Use | Basic problems with a fixed size | Preferred when the size comes from input |
Let us check the memory row with a small program. It asks one question: does the first element of row 1 sit right after the last element of row 0?
#include <iostream>
#include <vector>
using namespace std;
int main() {
int arr[2][3] = {{1, 2, 3}, {4, 5, 6}};
vector<vector<int>> vec = {{1, 2, 3}, {4, 5, 6}};
// Is The First Element Of Row 1 Right After The Last Element Of Row 0?
cout << boolalpha;
cout << "2D array: " << (&arr[0][2] + 1 == &arr[1][0]) << endl;
cout << "2D vector: " << (&vec[0][2] + 1 == &vec[1][0]) << endl;
return 0;
}
Output:
2D array: true 2D vector: false
In the 2D array, the two rows are glued together. In the 2D vector, they are not, because every row got its own memory when it was created. This does not make the 2D vector wrong or slow for homework. It only explains why a 2D vector can have rows of different lengths, and why it is a little less cache-friendly than a plain array on very large data.
How To Declare 2D Vector In CPP?
There are mainly three methods to declare a 2D vector in C++. One of them, the empty 2D vector, has already been shown in the code snippet above.
There are two more methods by which we can declare the 2D vector. If you want every way to set up a normal 1D vector as well, we have a separate guide on how to initialize a vector in C++.
2D Vector Initialization With Value
In this method, the 2D vector is initialized directly with predefined values. This means you don't have to insert elements later; everything is set up at the time of declaration itself.
Before initializing a 2D vector, make sure to include the required headers in your program, especially the <vector> header file.
// Example Of 2D Vector Declaration Along With Data
#include <vector>
#include <iostream>
using namespace std;
int main()
{
vector<vector<int>> v{{1, 2, 3}, {4, 5, 6}};
cout << "Rows: " << v.size() << ", Columns: " << v[0].size() << endl;
return 0;
}
Output:
Rows: 2, Columns: 3
Here, using the above syntax, we declare a 2D vector of int which holds some values. We use the inner braces to mark each row. So {1, 2, 3} is row 0 and {4, 5, 6} is row 1. We also printed the row and column count so you can see the shape C++ built from the braces.
2D Vector Initialization With Row & Column Values
In this approach, the 2D vector is not declared by listing its elements. Instead, the size of the vector is defined by giving the number of rows and columns. This makes it easy to create a matrix-like structure without typing all the values at the beginning.
#include <vector>
#include <iostream>
using namespace std;
int main()
{
int rows = 3, cols = 4; // Row & Column Values In Separate Variables
// rows Copies Of A Row That Has cols Zeros
vector<vector<int>> zap(rows, vector<int>(cols, 0));
for (int i = 0; i < zap.size(); i++)
{
for (int j = 0; j < zap[i].size(); j++)
cout << zap[i][j] << " ";
cout << endl;
}
return 0;
}
Output:
0 0 0 0 0 0 0 0 0 0 0 0
In the above case, the row & column numbers are kept in separate variables. Then we use two vector constructors together. The inner part, vector<int>(cols, 0), builds one row with 4 zeros. The outer part makes rows copies of that row. If you leave out the 0, the values still start at 0 for int, but writing it makes your intention clear to whoever grades your code.
It is easier to read this line from the inside out.
Bonus: Rows With Different Lengths (Jagged 2D Vector)
Since every row is its own vector, nothing forces the rows to be the same length. A 2D vector like this is called a jagged vector. A 2D array can't do this at all.
#include <vector>
#include <iostream>
using namespace std;
int main()
{
// Every Row Can Have Its Own Length
vector<vector<int>> zap{{1}, {2, 3}, {4, 5, 6}};
for (int i = 0; i < zap.size(); i++)
{
cout << "Row " << i << " has " << zap[i].size() << " element(s): ";
for (int j = 0; j < zap[i].size(); j++) // Always Use zap[i].size() Here
cout << zap[i][j] << " ";
cout << endl;
}
return 0;
}
Output:
Row 0 has 1 element(s): 1 Row 1 has 2 element(s): 2 3 Row 2 has 3 element(s): 4 5 6
Notice the inner loop uses zap[i].size() and not a fixed column number. If you had written j < 3 here, rows 0 and 1 would be read past their end. This habit prevents many crashes.
What Is The Process To Traverse Through 2D Vector In C++? How To Print A 2D Vector In CPP?
Traversing through a two-dimensional vector is a very simple process. It is like going through a 2D array. We use a nested for loop to visit every element. But first, we need a 2D vector with some data in it.
Code for traversal:
#include <vector>
#include <iostream>
using namespace std;
int main()
{
vector<vector<int>> zap{{20, 7}, {23, 20}}; // Initialization Of Vector Inside Vector
cout << "Traversal Of 2D Vector: " << endl;
for (int i = 0; i < zap.size(); i++) // Outer For Loop For Displaying Vector
{
for (int j = 0; j < zap[i].size(); j++) // Inner Loop For Displaying Vector
cout << zap[i][j] << " ";
cout << endl;
}
return 0;
}
Steps of The Program:
- At first, the vector and iostream header files are included in the program.
- A sample 2D vector along with the data is declared in the program.
- Two nested loops are declared. There is an outer loop and an inner loop.
- The outer loop picks the row, and the inner loop prints every element of that row. After each row,
endlmoves the output to a new line.
Output:
Traversal Of 2D Vector: 20 7 23 20
As this is a traversing operation, or in simple words, a print operation, the data that we provided in the 2D vector gets printed row by row.
A small note on the values. You may see code that writes 07 instead of 7. It prints the same thing, but a number that starts with 0 is read by C++ as an octal (base 8) number. That works for 07, but the moment someone types 08, the code stops compiling:
main.cpp:5:34: error: invalid digit "8" in octal constant
So don't put a leading zero in front of numbers in C++, even if it makes a date look nicer.
Shorter Way: Range-Based For Loop
If you only need to read the values and don't care about the index numbers, a range-based for loop is shorter and harder to get wrong. Many C++ programmers write it this way today.
#include <vector>
#include <iostream>
using namespace std;
int main()
{
vector<vector<int>> zap{{20, 7}, {23, 20}};
for (const auto& row : zap) // Each row Is One Inner Vector
{
for (int value : row) // Each value Is One Element Of That Row
cout << value << " ";
cout << endl;
}
return 0;
}
Output:
20 7 23 20
The const auto& part is worth remembering. Without the &, C++ copies every row into row before printing it. The output looks the same, but on a big matrix you are copying the whole thing for no reason. The const makes sure you don't change anything by mistake while printing.
Sorting and traversing a 2D vector can be tricky for beginners. If your C++ assignment is stuck on a loop that keeps crashing, one of our C++ experts can walk you through it.
How To Sort 2D Vector In CPP?
There is no special sorting function made only for a 2D vector. But the regular sort() function from the <algorithm> header works on it, as long as you understand what it compares. Let us first look at the classic example.
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
int main() {
vector<vector<int>> zap = {{7, 8, 9}, {4, 5, 6}, {1, 2, 3}}; // Unsorted 2D Vector
sort(zap.begin(), zap.end()); // Sorting The 2D Vector
// Printing The 2D Vector
cout << "Sorted 2D vector:" << endl;
for (int i = 0; i < zap.size(); i++) // Outer For Loop For Displaying Vector
{
for (int j = 0; j < zap[i].size(); j++) // Inner Loop For Displaying Vector
cout << zap[i][j] << " ";
cout << endl;
}
return 0;
}
Steps of The Program:
- At first, the vector and algorithm header files are included in the program, so we can use the
sort()function. - A 2D vector is declared along with some values in a mixed order.
- Now, the
sort()function is used from the beginning to the end of the outer vector. - Now, we traverse and print the values in the 2D vector as we discussed earlier.
Output:
Sorted 2D vector: 1 2 3 4 5 6 7 8 9
The rows came out in order, so it looks like the whole 2D vector got sorted. But there is one thing to understand: sort(zap.begin(), zap.end()) moves whole rows around. It never touches the numbers inside a row. It compares two rows the way a dictionary compares two words: first element first, and only if those are equal does it look at the second element, and so on.
The example above only worked so nicely because every row was already sorted inside. Look what happens with messier data:
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
void print(const vector<vector<int>>& zap) {
for (const auto& row : zap) {
for (int value : row)
cout << value << " ";
cout << endl;
}
}
int main() {
vector<vector<int>> zap = {{3, 9, 1}, {1, 7, 4}, {3, 2, 8}};
sort(zap.begin(), zap.end()); // Rows Are Compared Like Words In A Dictionary
cout << "Rows sorted:" << endl;
print(zap);
for (auto& row : zap) // Sorting The Inside Of Every Row
sort(row.begin(), row.end());
cout << "Each row sorted:" << endl;
print(zap);
return 0;
}
Output:
Rows sorted: 1 7 4 3 2 8 3 9 1 Each row sorted: 1 4 7 2 3 8 1 3 9
In the first result, the rows 3 2 8 and 3 9 1 both start with 3, so C++ checked the second values (2 and 9) to decide their order. The numbers inside each row stayed where they were. To sort the inside of the rows, we had to loop over the rows and call sort() on each one.
Sort A 2D Vector By A Specific Column
This is the version you will actually need in assignments. Say each row is one student: ID, midterm score, final score. The question asks you to rank students by their final score. You pass sort() a small comparison function (a lambda) that looks only at column 2.
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
int main() {
// Each Row: Student ID, Midterm Score, Final Score
vector<vector<int>> zap = {{101, 78, 85}, {102, 92, 88}, {103, 65, 91}};
// Sorting The Rows By Column 2 (Final Score), Highest First
sort(zap.begin(), zap.end(), [](const vector<int>& a, const vector<int>& b) {
return a[2] > b[2];
});
for (const auto& row : zap)
cout << "ID " << row[0] << " Midterm " << row[1] << " Final " << row[2] << endl;
return 0;
}
Output:
ID 103 Midterm 65 Final 91 ID 102 Midterm 92 Final 88 ID 101 Midterm 78 Final 85
Change a[2] > b[2] to a[1] < b[1] and the same code sorts by midterm score, lowest first. Only the column number and the sign change.
What Are The Major Operations That Can Be Done On 2D Vectors In C++?
The above discussion should clear your basic doubts about 2D vectors in C++. Now, let us understand the major operations that can be done on them. They are the following:
- Insert Elements Using The push_back() Method
- Remove Elements Using The pop_back() Method
- Access Any Element Using The at() Function
- Get The Number Of Rows, Columns, And Elements Using The size() Function
- Check Whether The Vector Is Empty Using The empty() Function
- Insert Or Erase A Row Or Column In The Middle
- Change The Size Using The resize() Function
Let us go through all of them one by one.
How To Insert Elements Using The push_back() Method?
The push_back() function adds a new item at the end of a vector. In a 2D vector, the "item" of the outer vector is a whole row. So when you call push_back() on the outer vector, you pass it a complete 1D vector, and that vector becomes the new last row.
It works like an append operation. In the example below, we start with an empty 2D vector and insert a 1D vector into it as its first row.
General Syntax: two-d-vector-name.push_back(one-d-vector-name);
Code To Implement Use Of The push_back() Method:
#include <vector>
#include <iostream>
using namespace std;
int main()
{
vector<vector<int>> zap; // 2D Vector Initialization
vector<int> one = {20, 7, 20, 23}; // 1D Vector Initialization With Values
zap.push_back(one); // Adding The Whole 1D Vector As A New Row
cout << "The 2D Vector Data Is: ";
for (int i = 0; i < zap.size(); i++) // Outer For Loop For Displaying Vector
{
for (int j = 0; j < zap[i].size(); j++) // Inner For Loop For Displaying Vector
cout << zap[i][j] << " ";
}
cout << endl;
return 0;
}
Steps Of The Program:
- At first, the 2D vector is declared without any value in it.
- Now, a simple single-dimensional vector is declared with some values.
- Now, we pass that single vector to
push_back(). A copy of it is added to the 2D vector as row 0. That is the reason the single vector's name is inside the parentheses. - Now, we traverse the 2D vector to print its values.
Output:
The 2D Vector Data Is: 20 7 20 23
From the above output, we can see that the 2D vector now holds all four values from the 1D vector as one row. The 2D vector did not need a size in advance. It simply grew by one row.
There is a second way to use push_back() that students mix up with the first one. You can also add a single number to the end of one row. The difference is only which vector you call it on:
#include <vector>
#include <iostream>
using namespace std;
int main()
{
vector<vector<int>> zap;
zap.push_back({1, 2, 3}); // Adds A New Row At The Bottom
zap.push_back({4, 5}); // Adds Another Row
zap[1].push_back(6); // Adds One Element At The End Of Row 1
for (const auto& row : zap)
{
for (int value : row)
cout << value << " ";
cout << endl;
}
return 0;
}
Output:
1 2 3 4 5 6
zap.push_back(...) adds a row. zap[1].push_back(...) adds one value to row 1. When a program ends up with extra rows or missing columns, this mix-up is usually the reason.
How To Remove Elements Using The pop_back() Method?
Just like there is a built-in function to add elements to a 2D vector, there is also a built-in function to remove them. That is the pop_back() method. It removes the last item of whichever vector you call it on.
Here, everything depends on the index number. Index 0 is the first row, index 1 is the second row, and index 2 is the third row. So zap[0].pop_back() removes the last value of the first row.
General Syntax: vector-name[row-index].pop_back();
Code To Implement Use Of The pop_back() Method:
#include <vector>
#include <iostream>
using namespace std;
void print(const vector<vector<int>>& zap) {
for (int i = 0; i < zap.size(); i++) // Outer For Loop For Displaying Vector
{
for (int j = 0; j < zap[i].size(); j++) // Inner Loop For Displaying Vector
cout << zap[i][j] << " ";
cout << endl;
}
}
int main()
{
vector<vector<int>> zap{{20, 7}, {23, 20}}; // Initialization Of Vector Inside Vector
cout << "Original 2D Vector: " << endl;
print(zap);
zap[0].pop_back(); // Removing Last Element Of First Row
zap[1].pop_back(); // Removing Last Element Of Second Row
cout << "2D Vector After Element Removing: " << endl;
print(zap);
zap.pop_back(); // Removing The Whole Last Row
cout << "After Removing The Last Row: " << zap.size() << " row left" << endl;
return 0;
}
Steps Of The Program:
- Here, the two-dimensional vector is declared along with some values, like a small 2 x 2 matrix.
- Now, we print all the values that we provided. We moved the printing into a small
print()function so we don't have to write the nested loop three times. - Now, we use the above syntax to remove elements one by one. First, the last element of the first row is removed. Then, the last element of the second row is removed in the same way.
- The data is printed again. The removed elements are no longer there.
- At last, we call
pop_back()on the outer vector, which removes the entire last row.
Output:
Original 2D Vector: 20 7 23 20 2D Vector After Element Removing: 20 23 After Removing The Last Row: 1 row left
From the above output, we can see that the two-dimensional vector works properly after removing elements. In the first case, it prints all the data. In the second case, only the remaining data is printed. One warning: calling pop_back() on a row that is already empty is undefined behavior, so check empty() first if you are not sure.
How To Access Elements Using The at() Method In A CPP 2D Vector?
The at() function is a built-in function of the vector class. In a 2D vector, we call it twice: first to pick the row, then to pick the column. The use of the at() function is as easy as you think.
Syntax: vector-name.at(row-number).at(column-number)
Code To Implement The at() Function In A 2D Vector:
#include <iostream>
#include <vector>
#include <stdexcept>
using namespace std;
int main() {
vector<vector<int>> zap = {{1, 2, 3}, {4, 5, 6}}; // Creating A 2D Vector
// Accessing Elements Using at() Operation
int e = zap.at(0).at(1);
cout << "Row 0 & Column 1 Element: " << e << endl; // Print The Result
try {
cout << zap.at(2).at(0) << endl; // There Is No Row 2
} catch (const out_of_range& ex) {
cout << "Error caught: " << ex.what() << endl;
}
return 0;
}
Steps of the Program:
- Declare a 2D vector in the program along with some values.
- Use the above syntax and store the element in a variable.
- Print the variable to get the result.
- Then try to read a row that does not exist, inside a
tryblock, and catch the error.
Output:
Row 0 & Column 1 Element: 2 Error caught: vector::_M_range_check: __n (which is 2) >= this->size() (which is 2)
From the above output, we can see that the value is 2. We asked for row 0, column 1, which is the second value of the first row. Remember that indexing starts from 0, so "row 0, column 1" means first row, second column.
The second line is the real reason to use at(). The vector has only rows 0 and 1, so asking for row 2 throws a std::out_of_range exception instead of reading random memory. The square brackets zap[2][0] would not check anything. The exact error text comes from the compiler's library, so on Visual Studio or on a Mac it will be worded differently, but the exception type is the same.
How To Find Rows, Columns, And Total Elements Using The size() Method?
The size() function is an important function. Using it, you can get the number of rows as well as the number of columns. To get the total number of elements, we need one extra step, because size() on the outer vector only counts rows.
Syntax for Rows: vector-name.size()
Syntax for Columns: vector-name.at(row-number).size()
Code To Demonstrate The Use Of size() In A Rectangular 2D Vector:
#include <iostream>
#include <vector>
using namespace std;
int main() {
vector<vector<int>> zap = {{1, 2, 3}, {4, 5, 6}}; // Creating A 2D Vector
int r = zap.size(); // Row Number
int c = zap.at(0).size(); // Column Number
cout << "Number of Rows: " << r << endl; // Print The Row Result
cout << "Number of Columns: " << c << endl; // Print The Column Result
cout << "Total Elements: " << r * c << endl;
return 0;
}
Steps of The Program:
- Here, the 2D vector is declared along with some values.
- Now, we take the number of rows from the outer vector and the number of columns from row 0.
- As every row has the same length here (a rectangular 2D vector), we can multiply the two values to get the total.
- We print each value.
Output:
Number of Rows: 2 Number of Columns: 3 Total Elements: 6
From the above output, the number of rows is 2 and the number of columns is 3, so there are six elements in total.
But rows times columns only works when every row has the same length. In a jagged 2D vector, you have to add up the size of each row instead:
#include <iostream>
#include <vector>
using namespace std;
int main() {
vector<vector<int>> zap = {{1}, {2, 3}, {4, 5, 6}}; // Rows Of Different Length
int total = 0;
for (const auto& row : zap)
total += row.size(); // Adding Up The Size Of Every Row
cout << "Rows: " << zap.size() << endl;
cout << "Total Elements: " << total << endl;
return 0;
}
Output:
Rows: 3 Total Elements: 6
If we had multiplied 3 rows by the size of row 0 (which is 1), we would have got 3, which is wrong. Adding the rows gives the correct answer of 6.
How To Check The Empty Status Using empty() In A CPP 2D Vector?
Like every container, a vector has a function to check whether it is empty or not. The use of the empty() function is the easiest among all the operations we have discussed so far.
Syntax: vector-name.empty()
C++ Program To Show The Use Of The empty() Function For A 2D Vector:
#include <iostream>
#include <vector>
using namespace std;
int main() {
vector<vector<int>> zap = {{1, 2, 3}, {4, 5, 6}}; // Creating A 2D Vector
if (zap.empty()) // If 2D Vector Is Empty
cout << "The 2D Vector Is Empty" << endl;
else // If 2D Vector Is Not Empty
cout << "The 2D Vector Is Not Empty" << endl;
vector<vector<int>> one(3); // Three Rows, But Every Row Is Empty
cout << "one.empty(): " << (one.empty() ? "true" : "false") << endl;
cout << "one[0].empty(): " << (one[0].empty() ? "true" : "false") << endl;
return 0;
}
Steps of The Program:
- The 2D vector is declared along with some values to check the
empty()function. - Now, we use an if-else statement.
- If the vector is empty, the first message is displayed.
- Otherwise, the "Not Empty" message is displayed.
- Then we make a second 2D vector with 3 rows but no values, and check it too.
Output:
The 2D Vector Is Not Empty one.empty(): false one[0].empty(): true
From the first line, we can see the "Not Empty" result. There are values in the vector, so the if statement doesn't run and the else statement does.
The last two lines are the tricky part. The vector one has 3 rows, so one.empty() says false, even though there is not a single number in it. Its rows are empty. If a question asks "does the matrix have any data?", checking only the outer vector is not enough.
How To Insert Or Erase A Row Or Column In The Middle?
push_back() and pop_back() only work at the end. To add or remove a row somewhere in the middle, use insert() and erase() on the outer vector. A column is different. Since there is no single "column" object in a 2D vector, you have to change every row one at a time.
#include <iostream>
#include <vector>
using namespace std;
void print(const vector<vector<int>>& zap) {
for (const auto& row : zap) {
for (int value : row)
cout << value << " ";
cout << endl;
}
cout << "--" << endl;
}
int main() {
vector<vector<int>> zap = {{1, 2, 3}, {7, 8, 9}};
zap.insert(zap.begin() + 1, {4, 5, 6}); // New Row At Index 1
print(zap);
zap.erase(zap.begin()); // Removing Row 0
print(zap);
for (auto& row : zap) // Removing Column 1 From Every Row
row.erase(row.begin() + 1);
print(zap);
for (auto& row : zap) // Adding A New Column At The End
row.push_back(0);
print(zap);
return 0;
}
Output:
1 2 3 4 5 6 7 8 9 -- 4 5 6 7 8 9 -- 4 6 7 9 -- 4 6 0 7 9 0 --
Reading the output block by block: the new row 4 5 6 went in at index 1, then row 0 was removed, then the middle value of each row (column 1) was removed, and at last a 0 was added to the end of each row as a new column. zap.begin() + 1 means "the position of index 1". The same pattern works for any index.
How To Change The Size Using resize()?
The resize() function grows or shrinks a vector to the size you give it. On the outer vector, it changes the number of rows. On each row, it changes the number of columns. You can also tell it what value the new spots should get.
#include <iostream>
#include <vector>
using namespace std;
int main() {
vector<vector<int>> zap = {{1, 2}, {3, 4}};
zap.resize(3, vector<int>(2, 0)); // Grow To 3 Rows; The New Row Is All Zeros
for (auto& row : zap)
row.resize(4, 9); // Grow Every Row To 4 Columns; New Spots Get 9
for (const auto& row : zap) {
for (int value : row)
cout << value << " ";
cout << endl;
}
return 0;
}
Output:
1 2 9 9 3 4 9 9 0 0 9 9
The old values 1, 2, 3, and 4 stayed where they were. The new third row started as two zeros, and then every row got two more spots filled with 9. If you call resize() with a smaller number, the extra values at the end are removed.
Passing A 2D Vector To A Function
Sooner or later, an assignment will ask you to write functions like printMatrix() or addMatrices(). This is where many students lose points, because the function seems to work but the changes never show up in main().
#include <iostream>
#include <vector>
using namespace std;
void addBonusCopy(vector<vector<int>> grid) { // Receives A Copy
grid[0][0] += 10;
}
void addBonus(vector<vector<int>>& grid) { // Receives The Original
grid[0][0] += 10;
}
int main() {
vector<vector<int>> zap = {{70, 80}, {90, 60}};
addBonusCopy(zap);
cout << "After addBonusCopy: " << zap[0][0] << endl;
addBonus(zap);
cout << "After addBonus: " << zap[0][0] << endl;
return 0;
}
Output:
After addBonusCopy: 70 After addBonus: 80
addBonusCopy() received a full copy of the 2D vector, changed the copy, and threw it away when the function ended. addBonus() has an & in its parameter, so it worked on the original. The rule is simple:
- If the function needs to change the 2D vector, use
vector<vector<int>>&. - If the function only reads it (like printing), use
const vector<vector<int>>&. You still avoid the copy, and the compiler stops you from changing it by accident.
You may have noticed we already did this with the print() function in the pop_back() and sort examples above.
Real Assignment Question: Creating A 2D Vector With User-Defined Size
From our experience, apart from the different operations on a C++ 2D vector, another question you can expect in labs and exams is to create a 2D vector with a user-defined size.
It comes up often in lab tests and competitive programming because a fixed-size array can't solve it cleanly. Here is the implementation for this question.
#include <iostream>
#include <vector>
using namespace std;
int main()
{
int rows, cols;
// Taking The Row Number
cout << "Enter Number Of Rows: ";
cin >> rows;
// Taking The Column Number
cout << "Enter Number Of Columns: ";
cin >> cols;
// Creating A 2D Matrix Using Vector
vector<vector<int>> matrix(rows, vector<int>(cols));
cout << "Enter The Matrix Elements Row-Wise:\n";
for (int i = 0; i < rows; i++)
for (int j = 0; j < cols; j++)
cin >> matrix[i][j];
cout << "\nEntered Matrix Is:\n";
for (int i = 0; i < rows; i++)
{
for (int j = 0; j < cols; j++)
cout << matrix[i][j] << " ";
cout << endl;
}
return 0;
}
The program first asks the user to enter the number of rows for the matrix. Then it asks for the number of columns.
A 2D vector (matrix) is created using the given rows and columns. The user is then asked to enter the matrix elements row by row. Finally, the program displays the matrix so the user can verify the input. Here is a run where we entered 2 rows, 3 columns, and the values 1 to 6:
Enter Number Of Rows: 2 Enter Number Of Columns: 3 Enter The Matrix Elements Row-Wise: 1 2 3 4 5 6 Entered Matrix Is: 1 2 3 4 5 6
This approach is clean, easy to debug, and works for most student assignments.
There is one weak spot, though. If the user types 0, a negative number, or a letter for the rows, the program misbehaves. A negative number can even make the program throw an exception and stop. Some instructors test this on purpose. Here is a version that keeps asking until the size makes sense:
#include <iostream>
#include <vector>
using namespace std;
int main()
{
int rows, cols;
// Keep Asking Until The User Gives A Size Above Zero
cout << "Enter Number Of Rows: ";
while (!(cin >> rows) || rows <= 0) {
cin.clear(); // Clear The Error If A Letter Was Typed
cin.ignore(1000, '\n'); // Throw Away The Bad Line
cout << "Rows must be a whole number above 0. Try again: ";
}
cout << "Enter Number Of Columns: ";
while (!(cin >> cols) || cols <= 0) {
cin.clear();
cin.ignore(1000, '\n');
cout << "Columns must be a whole number above 0. Try again: ";
}
vector<vector<int>> matrix(rows, vector<int>(cols));
cout << "Created a " << matrix.size() << " x " << matrix[0].size() << " matrix." << endl;
return 0;
}
And here is what happened when we typed -2 and "abc" for the rows, then 0 for the columns:
Enter Number Of Rows: -2 Rows must be a whole number above 0. Try again: abc Rows must be a whole number above 0. Try again: 3 Enter Number Of Columns: 0 Columns must be a whole number above 0. Try again: 4 Created a 3 x 4 matrix.
cin.clear() resets cin after it fails to read a number, and cin.ignore() throws away the bad text. Without those two lines, typing "abc" makes the loop print the same message forever.
Follow-Up Question: Transpose Of A Matrix
Once the matrix is read, the next part of the question is often to transpose it, which means rows become columns. The detail students miss is that a 2 x 3 matrix becomes a 3 x 2 matrix, so the result vector must be created with the sizes swapped.
#include <iostream>
#include <vector>
using namespace std;
int main()
{
vector<vector<int>> matrix = {{1, 2, 3}, {4, 5, 6}}; // 2 Rows, 3 Columns
int rows = matrix.size();
int cols = matrix[0].size();
// The Transpose Has The Sizes Swapped: 3 Rows, 2 Columns
vector<vector<int>> result(cols, vector<int>(rows));
for (int i = 0; i < rows; i++)
for (int j = 0; j < cols; j++)
result[j][i] = matrix[i][j]; // Row i Becomes Column i
for (const auto& row : result)
{
for (int value : row)
cout << value << " ";
cout << endl;
}
return 0;
}
Output:
1 4 2 5 3 6
If you create result with the same size as matrix, the line result[j][i] writes outside the vector as soon as j reaches 2, and the program may crash or print garbage.
Where Jagged 2D Vectors Show Up: Graphs
Jagged 2D vectors are used in real programs too. The most common place you will meet one is a graph stored as an adjacency list. Each row belongs to one node and holds the list of nodes it connects to. Some nodes have many neighbors and some have one, so the rows naturally have different lengths.
#include <iostream>
#include <vector>
using namespace std;
int main() {
int n = 4; // Four Cities: 0, 1, 2, 3
vector<vector<int>> adj(n); // Four Empty Rows, One Per City
// Each Road Goes Both Ways, So We Add It To Both Rows
int roads[][2] = {{0, 1}, {0, 2}, {0, 3}, {2, 3}};
for (auto& r : roads) {
adj[r[0]].push_back(r[1]);
adj[r[1]].push_back(r[0]);
}
for (int city = 0; city < n; city++) {
cout << "City " << city << " connects to:";
for (int next : adj[city])
cout << " " << next;
cout << endl;
}
return 0;
}
Output:
City 0 connects to: 1 2 3 City 1 connects to: 0 City 2 connects to: 0 3 City 3 connects to: 0 2
vector<vector<int>> adj(n) creates 4 empty rows, and push_back() fills each row as we read the roads. This is the same structure used in shortest path programs such as Dijkstra's algorithm in C++, so it is worth getting comfortable with it now.
2D Vector Or One Flat Vector?
When every row has the same length and the matrix is large (think image pixels or a big game board), some programmers skip the 2D vector and store everything in one 1D vector. Since all values sit in one block, it is usually faster to go through, and you calculate the position yourself.
#include <iostream>
#include <vector>
using namespace std;
int main() {
int rows = 2, cols = 3;
vector<int> grid(rows * cols, 0); // One Single Vector Holds The Whole Matrix
// Element (r, c) Lives At Index r * cols + c
grid[1 * cols + 2] = 7; // Same As grid[1][2] In A 2D Vector
for (int r = 0; r < rows; r++) {
for (int c = 0; c < cols; c++)
cout << grid[r * cols + c] << " ";
cout << endl;
}
return 0;
}
Output:
0 0 0 0 0 7
For most homework, the regular 2D vector is the better choice because the code is easier to read and grade. But if your assignment talks about performance or memory layout, the flat version and the r * cols + c formula are good to know.
Common Mistakes Students Make With 2D Vectors In Exams
Most errors with 2D vectors are not advanced mistakes. They are small logical issues that students run into again and again during exams, labs, and assignments. Keep this list in mind before your next lab.
- Sometimes, students access the elements of a 2D vector before giving it a size, which causes runtime errors. (Example below.)
- Often, students use the wrong loop limits, such as using the column size for rows or the other way around.
- Many times, students assume that
vector.size()gives the total number of elements instead of just the number of rows. - We have seen many times that students use
push_back()on the wrong vector and end up with extra rows or missing columns. - Sometimes, students write nested loops without checking
vector[i].size(), which causes crashes in jagged 2D vectors. - Students pass the 2D vector to a function without
&, and then wonder why their changes disappeared.
Here is the first mistake in action. The vector is declared, but it has no rows, and the code writes to row 0 anyway:
#include <iostream>
#include <vector>
using namespace std;
int main() {
vector<vector<int>> zap; // No Rows Yet
zap[0][0] = 5; // Writing To A Row That Does Not Exist
cout << zap[0][0] << endl;
return 0;
}
Output:
Segmentation fault (core dumped)
The program compiled without any error or warning and then crashed when it ran. That is what makes this mistake annoying: the compiler can't catch it for you. The fix is to give the vector a size first, for example vector<vector<int>> zap(1, vector<int>(1));, or to use push_back() to add the row.
Conclusion
As we saw, it is very important to understand the "2D vectors in C++" concept.
Many students reach for a 2D array first because that is what they learned first, and forget that vectors exist. Then they get stuck the moment the size comes from user input, or the rows need different lengths. A 2D vector handles both of these without any extra work.
It is also worth getting the basics of C++ clear, like header files, references, and indexing from 0. In this topic alone, almost every bug we showed came from one of those basics, not from the 2D vector itself.
Key Takeaways:
- A vector works like a dynamic array where the size can change over time, and a 2D vector is a vector of vectors.
- Using an initializer list or uniform initialization, we can declare a 2D vector with values.
- We can also create it with a row and column count, like
vector<vector<int>> v(rows, vector<int>(cols, 0)). - Traversing or printing a 2D vector is done with nested loops or range-based for loops.
- The
sort()function from<algorithm>sorts the rows, not the values inside them. Use a comparator to sort by a column. - We can add a row or a single value using the
push_back()method. - We can remove elements or a whole row using the
pop_back()method. - To access an element safely, use the
at()function. It throws an error instead of reading bad memory. size()on the outer vector gives rows, andsize()on a row gives that row's columns.- We can check whether the vector is empty using the
empty()function, but remember that a vector with empty rows is not "empty". - Pass a 2D vector to functions by reference so changes stick and nothing gets copied.
If you're interested in real-world uses of vectors, check out these C++ project ideas to build hands-on experience with 2D vector operations. A tic-tac-toe board, a seat booking chart, or a simple maze game are all 2D vectors at heart.
Frequently Asked Questions
Is a 2D vector stored in memory the same way as a 2D array in C++?
No, a 2D vector is not stored in memory the same way as a 2D array. A 2D array uses one continuous block of memory, while in a 2D vector each row is a separate block. The values inside one row are still next to each other. This design makes 2D vectors more flexible but slightly less cache-friendly than a plain 2D array.
Can a 2D vector have rows with different numbers of columns?
Yes, a 2D vector can have rows of different sizes, and this is one of its biggest advantages. Such a structure is commonly called a jagged or irregular 2D vector. It is especially useful in real-world problems like graph adjacency lists or uneven datasets.
Why does a program crash when accessing elements of a 2D vector?
A program usually crashes when a 2D vector element is accessed outside its valid range. This often happens when the vector was never given a size, the loop conditions are wrong, or the code assumes every row has the same number of columns. Using at() instead of square brackets turns the crash into a clear out_of_range error.
How do I get the number of columns in a 2D vector?
Use v[0].size() to get the number of columns in row 0. If the rows can have different lengths, use v[i].size() for each row i. Make sure the vector has at least one row before calling v[0].size(), or the program has undefined behavior and may crash.
What is the difference between vector<vector<int>> v(n) and v(n, vector<int>(m))?
vector<vector<int>> v(n) creates n rows, but every row is empty, so v[0][0] is out of range. v(n, vector<int>(m)) creates n rows with m zeros in each, so you can use v[i][j] right away. Use the first one when you plan to fill the rows with push_back(), like an adjacency list.
How do I clear a 2D vector?
Call v.clear() to remove all rows at once, after which v.size() is 0. If you want to keep the rows but remove their values, loop over the rows and call clear() on each one instead.
