c++ - 为什么我收到未在此范围内声明的错误?
问题描述
#include<iostream>
#include<vector>
using namespace std;
int sol(int i,int j,vector<vector<char>>v,int h,int w,int dp[][w]){
if(i>h || j>w){
return 0;
}
if(i==h && j==w){
return 1;
}
if(v[i][j]=='#'){
return 0;
}
if(dp[i][j]!=-1){
return dp[i][j];
}
dp[i][j]=sol(i+1,j,v,h,w,dp) + sol(i,j+1,v,h,w,dp);
return dp[i][j];
}
int main(){
int h,w;
cin>>h>>w;
vector<vector<char>>v(h);
char c;
int dp[h][w];
for(int i=0;i<h;i++){
for(int j=0;j<w;j++){
cin>>c;
v[i].push_back(c);
dp[i][j]=-1;
}
}
h--;
w--;
cout<<sol(0,0,v,h,w,dp)<<endl;
}
为什么我收到错误,即 i,j,h,w,dp 未在此范围内声明(在 sol 函数内部)。如果我从代码中删除 dp[][] 数组,则它运行时不会出现任何错误https:// ideone.com/uqz3p3)
解决方案
在 C++ 中,数组边界必须是编译时常量。在您的代码int dp[][w]
w
中是一个变量,而不是一个常量。
由于您已经在使用向量,我建议您也使用向量dp
。在main
vector<vector<int>> dp(h, vector<int>(w));
并且在sol
int sol(int i,int j,vector<vector<char>>v,int h,int w,vector<vector<int>>& dp) {
推荐阅读
- ruby - 如何获取简单 Sequel Dataset 对象的表名?
- here-api - HereMaps API 端点返回带有换行符的 json
- laravel - Laravel 邮政编码查询
- c# - 使用参数调用存储过程以返回列表
- sql - 数据大小与查询执行
- advanced-custom-fields - ACF 中继器字段仅显示一行
- liferay - 如果 liferay 放置 30 分钟然后更新,则会出现 CSRF 令牌错误
- android - 前台服务不适用于 Oreo (Android 8.1.0)
- java - 在谷歌数据存储中的不同实体之间级联重复属性更改的最佳实践?
- php - 我必须在哪里包含我的应用程序的业务逻辑?