Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Assigning values to 2D Vector by using indices

I am trying to add values to a 2D vector by using both indices. When I run my program, I get the windows message saying the program has stopped working. Using Dev-C++ to debug showed that there was a segmentation fault (I am not sure what this means). Please do not suggest using arrays, I have to use vectors for this assignment.

#include <iostream>
#include <vector>
using namespace std;

int main(int argc, char** argv) { 

vector< vector<int> > matrix;
cout << "Filling matrix with test numbers.";
for (int i = 0; i < 4; i++) {
    for (int j = 0; j < 4; j++) {

        matrix[i][j] = 5; // causes program to stop working

    }
}
}

I have created a test case where I want to fill a 3X3 matrix with the value 5. I suspect that it has something to do with the size of the 2D vector not being specifically defined. How would I fill a 2D vector with values by using the indices?

like image 649
AvP Avatar asked Sep 19 '14 15:09

AvP


2 Answers

As written, this is problematic, you are trying to write to a vector for which you did not yet allocate memory.

Option 1 - Resize your vectors ahead of time

vector< vector<int> > matrix;
cout << "Filling matrix with test numbers.";
matrix.resize(4);  // resize top level vector
for (int i = 0; i < 4; i++)
{
    matrix[i].resize(4);  // resize each of the contained vectors
    for (int j = 0; j < 4; j++)
    {
        matrix[i][j] = 5;
    }
}

Option 2 - Size your vector when you declare it

vector<vector<int>>  matrix(4, vector<int>(4));

Option 3 - Use push_back to resize the vector as needed.

vector< vector<int> > matrix;
cout << "Filling matrix with test numbers.";
for (int i = 0; i < 4; i++)
{
    vector<int> temp;
    for (int j = 0; j < 4; j++)
    {
        temp.push_back(5);
    }
    matrix.push_back(temp);
}
like image 160
Cory Kramer Avatar answered Oct 22 '22 14:10

Cory Kramer


You have not allocated any space for your 2d vector. So in your current code, you are trying to access some memory that does not belong to your program's memory space. This will result in Segmentation Fault.

try:

 vector<vector<int> >  matrix(4, vector<int>(4));

If you want to give all elements the same value, you can try:

 vector<vector<int> >  matrix(4, vector<int>(4,5)); // all values are now 5
like image 45
taocp Avatar answered Oct 22 '22 16:10

taocp