Right Way of Passing a 2D vector as an argument to

2019-06-01 04:18发布

问题:

I'm trying to write a function that takes a 2D vector as an argument. This compiles just fine, but I get a segmentation fault whilst execution.

//http://www.codechef.com/problems/SUMTRIAN
#include<iostream>
#include<algorithm>
#include<vector>

using namespace std;

int max_sum_path(int maximum_rows,vector<vector<int> >& matrix,int row_index,int colm_index);

int main()
{
  vector<vector<int> > Triangle;
  int num_test_cases;
  cin>>num_test_cases;
  //to iterate over the test cases
  for(int i=0;i<num_test_cases;++i)
  {
    int max_rows;
    cin>>max_rows;
    //to build the 2d vector
    Triangle.resize(max_rows);
    for(int j=0;j<max_rows;++j)
    {
      Triangle[j].resize(j+1);
    }
    //get the input
    for(int j=0;j<max_rows;++j)
    {
      for(int k=0;k<=j;++k)
      {
        cin>>Triangle[j][k];
      }
    }
    cout<<max_sum_path(max_rows,Triangle,0,0)<<endl;
    Triangle.clear();
  }
  return 0;
}

int max_sum_path(int maximum_rows,vector<vector<int> >& matrix,int row_index,int colm_index)
{
  if(row_index >= maximum_rows || colm_index > row_index)
  {
    //we have reached a cell outside the Triangular Matrix
    return 0;
  }
  else
  {
    return matrix[row_index][colm_index] + max(max_sum_path(maximum_rows,matrix,row_index+1,colm_index), max_sum_path(maximum_rows,matrix,row_index+1,colm_index+1));
  }
}

Here's the error that this gives me when I run it.

    Program received signal SIGSEGV, Segmentation fault.
0x0000000000400e21 in max_sum_path (maximum_rows=3, matrix=..., row_index=3, colm_index=3) at sums_triangle.cpp:49
49          return matrix[row_index][colm_index] + max(max_sum_path(maximum_rows,matrix,row_index+1,colm_index), max_sum_path(maximum_rows,matrix,row_index+1,colm_index+1));

As a side note, when I tried using a 2D array instead of the vector I got a compile time error.

g++ -Wall sums_triangle.cpp -o sums_triangle
sums_triangle.cpp: In function ‘int main()’:
sums_triangle.cpp:28:46: error: cannot convert ‘int (*)[(((long unsigned int)(((long int)max_rows) + -0x00000000000000001)) + 1)][(((long unsigned int)(((long int)max_rows) + -0x00000000000000001)) + 1)]’ to ‘int**’ for argument ‘2’ to ‘int max_sum_path(int, int**, int, int)’

What is the right way to pass multidimensional vectors as arguments to functions.

回答1:

You're resizing the vectors incorrectly. For example:

for(int j=0;j<max_rows;++j)
{
  Triangle[i].resize(j+1);
}

You are resizing Triangle[i] multiple times here. Probably you meant to say

for(int j=0;j<max_rows;++j)
{
  Triangle[j].resize(j+1);
}


回答2:

Change

Triangle[i].resize(j+1);

to

Triangle[j].resize(j+1);