Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Assigning to a two dimensional vector in c++

Tags:

c++

2d-vector

#include<bits/stdc++.h>
using namespace std;
main()
{
    vector<vector<int> > v;
    for(int i = 0;i < 3;i++)
    {
        vector<int> temp;
        for(int j = 0;j < 3;j++)
        {
            temp.push_back(j);
        }
        //cout<<typeid(temp).name()<<endl;
        v[i].push_back(temp);
    }
 }

I am trying to assign to a two dimensional vector. I am getting the following error

No matching function for call to 
std ::vector<int>::push_back(std::vector<int> &)
like image 608
problem_solver Avatar asked Jul 21 '17 04:07

problem_solver


People also ask

How do you represent a two-dimensional vector?

One way to represent a two-dimensional vector is with vector components, which simply tell you how far the vector goes in each direction. For example, a vector with an x-component of 4 and a y-component of 3 that started at the origin would end at coordinates (4,3).

How do you initialize a 2D vector with fixed size?

To initialize a two-dimensional vector to be of a certain size, you can first initialize a one-dimensional vector and then use this to initialize the two-dimensional one: vector<int> v(5); vector<vector<int> > v2(8,v); or you can do it in one line: vector<vector<int> > v2(8, vector<int>(5));

How do you initialize a 2D vector with zeros?

A vector can be initialized with all zeros in three principal ways: A) use the initializer_list, B) use the assign() vector member function to an empty vector (or push_back()), or C) use int or float as the template parameter specialization for a vector of initially only default values.


2 Answers

Problem: Your vector v is empty yet and you can't access v[i] without pushing any vector in v.

Solution: Replace the statement v[i].push_back(temp); with v.push_back(temp);

like image 51
Itban Saeed Avatar answered Sep 28 '22 12:09

Itban Saeed


You can follow this process :

#include<bits/stdc++.h>
using namespace std;
int main()
{
    vector<vector<int> > v;
    for(int i = 0;i < 3;i++)
    {
        vector<int> temp;
        for(int j = 0;j < 3;j++)
        {
            temp.push_back(j);

        }
        //cout<<typeid(temp).name()<<endl;
        v.push_back(temp);
    }
    for(int i = 0; i < 3; i++){
        for(int j = 0; j < 3; j++){
            cout << v[i][j] << " ";
        }
        cout << endl;
    }
 }
like image 23
Md. Rezwanul Haque Avatar answered Sep 28 '22 13:09

Md. Rezwanul Haque