向量向量中的分段错误
Segmentation fault in vector of vector
我正在练习一个名为 the gold mine problem on GeeksForGeeks 的动态规划问题
我的代码
#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;
}
在一些未知的测试用例中,我遇到了分段错误
Runtime Error:
Runtime ErrorSegmentation Fault (SIGSEGV)
我确信我的代码没有访问任何负索引,因为当我使用下面的构造函数初始化 vector<vector<int>>
时代码有效。 (由于问题中矩阵大小的限制,我选择了20)
vector<vector<int>> v(20,vector<int>(20,0));
我不明白为什么我会遇到分段错误,因为我要确保没有使用我的 if-else 阶梯访问范围之外的索引。
else if(row==0)
add = max(v[row][column+1], v[row+1][column+1]);
问题说明明确指出只有一行是完全有效的。但是这段代码假定至少有两行。
如果输入是完全有效的 1 1 3 1 2 3
,这可能(并且很可能会)崩溃。
我正在练习一个名为 the gold mine problem on GeeksForGeeks 的动态规划问题
我的代码
#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;
}
在一些未知的测试用例中,我遇到了分段错误
Runtime Error: Runtime ErrorSegmentation Fault (SIGSEGV)
我确信我的代码没有访问任何负索引,因为当我使用下面的构造函数初始化 vector<vector<int>>
时代码有效。 (由于问题中矩阵大小的限制,我选择了20)
vector<vector<int>> v(20,vector<int>(20,0));
我不明白为什么我会遇到分段错误,因为我要确保没有使用我的 if-else 阶梯访问范围之外的索引。
else if(row==0)
add = max(v[row][column+1], v[row+1][column+1]);
问题说明明确指出只有一行是完全有效的。但是这段代码假定至少有两行。
如果输入是完全有效的 1 1 3 1 2 3
,这可能(并且很可能会)崩溃。