0

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;
}
Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335
  • 1
    Please post the full error message. – stark Jan 27 '20 at 13:55
  • 2
    `vec` starts out *empty*. Any indexing into `vec` leads to *undefined behavior*- – Some programmer dude Jan 27 '20 at 13:55
  • 3
    And please take some time to read [Why should I not #include ?](https://stackoverflow.com/questions/31816095/why-should-i-not-include-bits-stdc-h) as well as [Why is “using namespace std;” considered bad practice?](https://stackoverflow.com/questions/1452721/why-is-using-namespace-std-considered-bad-practice) – Some programmer dude Jan 27 '20 at 13:56

3 Answers3

3

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>());

Blaze
  • 16,736
  • 2
  • 25
  • 44
1

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
Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335
0

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;
}
TruthSeeker
  • 1,539
  • 11
  • 24