简体   繁体   English

向量中的分割错误

[英]Segmentation fault in vector of vector

I am practicing a dynamic programming problem called the gold mine problem onGeeksForGeeks我正在GeeksForGeeks上练习一个叫做金矿问题的动态规划问题
My code我的代码

#include <iostream>
#include<vector>
using namespace std;
int main() {
    ios_base::sync_with_stdio(false);
    cin.tie(NULL);
    int test,i,max_rows,max_columns,temp;
    cin >> test;
    for(i=1;i<=test;i++)
    {
        cin>>max_rows>>max_columns;
        vector<vector<int>> v;//(20,vector<int>(20,0));
        for(int row = 0; row<max_rows; row++)
        {
            v.push_back(vector<int>());
            for(int column = 0; column<max_columns; column++)
            {
                cin>>temp;
                v[row].push_back(temp);
            }
        }
        for(int column = max_columns-1;column>=0;column--)
        {
            for(int row=0; row<max_rows;row++)
            {
                int add;
                if(column>=(max_columns-1))
                    add = 0;
                else if(row==0)
                    add = max(v[row][column+1], v[row+1][column+1]);
                else if(row==(max_rows-1))
                    add = max(v[row-1][column+1], v[row][column+1]);
                else if(row>(max_rows-1))
                    add = 0;
                else
                    add = max(v[row-1][column+1], max(v[row][column+1],v[row+1][column+1]));
                v[row][column]+= add;
            }
        }
        int max_value = 0;
        for(int row = 0;row<max_rows;row++)
            if(max_value<v[row][0])
                max_value = v[row][0];
        
        cout<<max_value<<endl;
    }
    return 0;
}

On some unknown testcase I'm getting a Segmentation Fault在一些未知的测试用例中,我遇到了分段错误

Runtime Error: Runtime ErrorSegmentation Fault (SIGSEGV)运行时错误:运行时错误分段错误 (SIGSEGV)

I am sure that my code is not accessing any negative indexes as the code works when I initialize the vector<vector<int>> with the constructor below.我确信我的代码没有访问任何负索引,因为当我使用下面的构造函数初始化vector<vector<int>>时代码有效。 (I choose 20 due to the limits of the matrix size in the problem) (由于问题中矩阵大小的限制,我选择了20)

vector<vector<int>> v(20,vector<int>(20,0));

I fail to understand why I'm getting segmentation fault because I'm making sure no indexes outside the range are accessed with my if-else ladder.我不明白为什么会出现分段错误,因为我确保没有使用 if-else 阶梯访问范围之外的索引。

                else if(row==0)
                    add = max(v[row][column+1], v[row+1][column+1]);

The problem specification clearly states that it is perfectly valid to have only one row.问题规范明确指出,只有一行是完全有效的。 But this code assumes that there are at least two rows.但是这段代码假设至少有两行。

This can (and likely will) crash if the input is 1 1 3 1 2 3 , which is perfectly valid input.如果输入是1 1 3 1 2 3 ,这可能(并且可能会)崩溃,这是完全有效的输入。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM