I have a vector and want to store int data in to it at run time can I store the data in a 2D vector in this manner ?
std::vector<std::vector <int>> normal:
for(i=0;i<10;i++){
for(j=0;j<20;j++){
normal[i].push_back(j);
}
}
Insertion in Vector of VectorsElements can be inserted into a vector using the push_back() function of C++ STL. Below example demonstrates the insertion operation in a vector of vectors. The code creates a 2D vector by using the push_back() function and then displays the matrix.
2D vectors are often treated as a matrix with “rows” and “columns” inside it. Under the hood they are actually elements of the 2D vector. We first declare an integer variable named “row” and then an array named “column” which is going to hold the value of the size of each row.
Yes, but you also need to push each of the sub-vectors:
std::vector<std::vector<int>> normal;
for(int i=0; i<10; i++)
{
normal.push_back(std::vector<int>());
for(int j=0; j<20; j++)
{
normal[i].push_back(j);
}
}
create a temporary vector push elements into this temporary vector and then push this temporary vector(v2 in my code) into a 2d vector(v1 in my code).
#include <iostream>
#include <bits/stdc++.h>
#include<algorithm>
using namespace std;
int main()
{
vector<vector<int>> v1;
vector<int> v2;
v2.push_back(1);
v2.push_back(2);
v2.push_back(13);
v2.push_back(14);
v2.push_back(15);
v1.push_back(v2);
//i pushed v2 into v1
int j=0;
for(int i=0 ; i<5 ;i++)
{
cout<<v1[0][i]<<"\t";
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With