In this article, we are going to learn how to insert elements in 2D vector in C++ language. This is an exercise to create a 2-dimensional vector with variable size and flexibility. As you might know in a 2 D vector, we can insert an element in each of its vectors, and also we can insert a full vector with multiple elements in a vector to grow the size of its dimension.
How to insert elements in 2D vector in C++
- Insert a vector in a 2 D vector in C++.
- Insert single element in vector that is part of a 2 D vector in C++.
1. Insert a vector in a 2 D vector in C++
In our first example, we will take an empty vector of vectors and we will create a square vector of vectors of size entered by the user by inserting elements at runtime. so let us see how this works.
#include <iostream>
#include <vector>
using namespace std;
int main()
{
// empty 2 D vector
vector<vector<int> > vec;
int size ;
int num = 1;
cout<< "Please insert the size for a square matrix :";
cin >> size;
for (int i = 0; i < size; i++)
{
vector<int> v1;
for (int j = 0; j < size; j++) {
v1.push_back(num);
num ++;
}
vec.push_back(v1);
}
for (int i = 0; i < vec.size(); i++) {
for (int j = 0; j < vec[i].size(); j++)
cout << vec[i][j] << " ";
cout << endl;
}
return 0;
}
Output
Please insert the size for a square matrix :4
1 2 3 4
5 6 7 8
9 10 11 12
13 14 15 16
2.Insert single element in vector that is part of a 2 D vector in C++
In our second example, we are going to add an element to a vector that is already part of a 2 D vector. In this example, we will understand how we can access the elements of a vector inside a 2 D vector. so first we will create a 2 D vector, which will have a size of 3×3. Then we will add 3 vectors to it with each vector having 3 elements.
This is our starting point, now our task is to add one more element to each of the 3 vectors which are part of this 3×3 2 D vector.
#include <iostream>
#include <vector>
using namespace std;
#define SIZE 3
int main()
{
// empty 2 D vector
vector<vector<int> > vec;
int size = SIZE;
int num = 1;
for (int i = 0; i < size; i++)
{
vector<int> v1;
for (int j = 0; j < size; j++) {
v1.push_back(num);
num ++;
}
vec.push_back(v1);
}
for (int i = 0; i < vec.size(); i++) {
for (int j = 0; j < vec[i].size(); j++)
cout << vec[i][j] << " ";
cout << endl;
}
for (int k = 0 ;k < vec.size(); k++)
{
vec[k].push_back(100);
}
for (int i = 0; i < vec.size(); i++) {
for (int j = 0; j < vec[i].size(); j++)
cout << vec[i][j] << " ";
cout << endl;
}
return 0;
}
Output
1 2 3 4 100
5 6 7 8 100
9 10 11 12 100
13 14 15 16 100