unable of get output from a 2d vector because of runtime error

253 views Asked by At

i am writing a program that will intake value of a 2 dimensional vector and provide them a output.But,i am getting a runtime error.

#include <bits/stdc++.h>
using namespace std;
int main() {
// your code goes here
vector<vector<int> > vec;
vec[0].push_back(1);
vec[0].push_back(2);
vec[0].push_back(13);

for(int i=0;i<3;i++)
{
    cout<<vec[0][i]<<" ";
}
return 0;
}
3

There are 3 answers

0
Blaze On

Your vector of vectors is empty. You can't do vec[0].push_back(1); because vec[0] doesn't exist. You can solve that problem by making your vector of vectors with a size of at least 1 by specifying that in the constructor. Change this

vector<vector<int> > vec;

To this:

vector<vector<int> > vec(1);

Alternatively you could push_back a vector into your vector of vectors:

vec.push_back(std::vector<int>());

0
TruthSeeker On

extending the answer,

you even can allocate a row vector and add to the main vector. with which you can add new the rows,

int main() {           
    vector<int> v1;
    v1.push_back(1);
    v1.push_back(2);
    v1.push_back(13);

    vector<vector<int>> vec;
    vec.push_back(v1);

    for (int i = 0; i < 3; i++)
    {
        cout << vec[0][i] << " ";
    }
    return 0;
}
0
Vlad from Moscow On

You declared an empty vector

vector<vector<int> > vec;

So you may not use the subscript operator like

vec[0].push_back(1);

You could declare the vector having at least one element of the type std::vector<int> like

vector<vector<int> > vec( 1 );

In any case you could declare and initialize the vector in one statement as it is shown in the demonstrative program below.

#include <iostream>
#include <vector>

int main() 
{
    std::vector<std::vector<int>> vec = { 1, { 1, 2, 13 } };

    for ( const auto &item : vec[0] ) std::cout << item << ' ';
    std::cout << '\n';

    return 0;
}

The program output is

1 2 13