How to Insert Elements into 2D Vector in C++? (original) (raw)
Last Updated : 23 Jul, 2025
In C++, 2D vectors provide several built-in methods to insert elements. The efficiency of the insertion depends on where the insertion occurs. In this article, we will explore different ways to insert elements into a 2D vector in C++ and their specific use cases.
The simplest way to add elements to a 2D vector is by appending the rows of elements (1D vectors) to the end using the **vector push_back() method. Let's take a look at an example:
C++ `
#include <bits/stdc++.h> using namespace std;
int main() { vector<vector> v = {{1, 2, 3}, {4, 5, 6}};
// Adding a new row at the end
v.push_back({7, 8, 9});
// Adding an element to the last row
v[2].push_back(10);
for (const auto& i : v) {
for (int j : i)
cout << j << " ";
cout << endl;
}
return 0;}
`
Output
1 2 3 4 5 6 7 8 9 10
Inserting elements in the middle is an expensive operation in a vector because all elements after the insertion point need to be shifted.
Using Vector insert()
The vector insert() method is versatile and can insert elements at any position in a 2D vector. It can also insert multiple elements simultaneously.
C++ `
#include <bits/stdc++.h> using namespace std;
int main() { vector<vector> v = {{1, 3, 5}, {7, 9, 11}};
// Inserting a new row at position 1
v.insert(v.begin() + 1, {4, 6, 8});
// Inserting a value into 2nd row at position 2
v[1].insert(v[1].begin() + 2, 10);
for (const auto& i : v) {
for (int j : i)
cout << j << " ";
cout << endl;
}
return 0;}
`
Output
1 3 5 4 6 10 8 7 9 11
Using vector emplace()
The **vector emplace() method works similarly to vector insert(), but instead of copying an element, it constructs the element directly in the vector. This avoids unnecessary copies, improving performance.
C++ `
#include <bits/stdc++.h> using namespace std;
int main() { vector<vector> v = {{1, 3, 5}, {7, 9, 11}};
// Emplacing a new row at position 1
v.emplace(v.begin() + 1, vector<int>{4, 6, 8});
// Emplacing value into 2nd row at position 2
v[1].emplace(v[1].begin() + 2, 10);
for (const auto& i : v) {
for (int j : i)
cout << j << " ";
cout << endl;
}
return 0;}
`
Output
1 3 5 4 6 10 8 7 9 11
Using vector emplace_back()
The vector emplace_back() method is the emplacing counterpart of push_back(). It constructs the new element directly in the vector, avoiding extra copies.
C++ `
#include <bits/stdc++.h> using namespace std;
int main() { vector<vector> v = {{1, 3, 5}, {7, 9, 11}};
// Emplacing a new row at the end
v.emplace_back(vector<int>{4, 6, 8});
// Emplacing a value in the last row
v[2].emplace_back(10);
for (const auto& i : v) {
for (int j : i)
cout << j << " ";
cout << endl;
}
return 0;}
`
Output
1 3 5 7 9 11 4 6 8 10