-4

I want to use vector header file but I guess there is an error in it. I have attached the image file containing the error. When ever I run this code I get the error shown in the image. Please tell me how to resolve it.

#include <iostream>
#include <conio.h>
#include <vector>

using namespace std;
int main()
{
vector<vector<int>> rmat;
vector<int> r = { 1, 2, 3, 4, 5 };

for (int i = 0; i < 3; i++)
for (int j = 0; j < 5; j++)
{
    rmat[i][j] = r[j];
}

for (int i = 0; i < 3; i++)
{
    for (int j = 0; j < 5; j++)
        cout << rmat[i][j] << "\t";
    cout << "\n";
}


_getch();
return 0;
}

Error on runtime

quamrana
  • 37,849
  • 12
  • 53
  • 71
user3322848
  • 30
  • 1
  • 8
  • 1
    You instantiated the `rmat` vector but didn't specify a size, therefore none was allocated, and you're accessing memory that does not exist yet. – Ryp Jun 04 '15 at 11:25
  • Your `rmat` is empty, yet you try to access elements in it (`rmat[i][j]`). – simon Jun 04 '15 at 11:26
  • i have to assign a rmat vector first. can i initialized using a variable – user3322848 Jun 05 '15 at 07:44

1 Answers1

1

Read the error message:

vector subscript out of range

You have created an empty vector,

vector<vector<int>> rmat;

and then access its nonexisting elements,

rmat[i][j] = r[j];

which results in this undefined behaviour which in you case resulted in a helpful exception being thrown.

Grab a good book on C++ and learn the basics first.

Community
  • 1
  • 1
rubenvb
  • 74,642
  • 33
  • 187
  • 332