Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I push_back data in a 2d vector of type int

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);
    }
}
like image 203
saru Avatar asked Feb 15 '17 12:02

saru


People also ask

Can we use Push_back in 2D vector?

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.

How do you declare a 2D array in vector?

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.


2 Answers

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);    
    }
}
like image 188
SingerOfTheFall Avatar answered Oct 22 '22 17:10

SingerOfTheFall


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";
    }
  }
like image 33
tinku kalluri Avatar answered Oct 22 '22 17:10

tinku kalluri