首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >应为'[‘标记前的主表达式..还有更多

应为'[‘标记前的主表达式..还有更多
EN

Stack Overflow用户
提问于 2021-05-05 20:40:31
回答 1查看 228关注 0票数 0

我一直在尝试在c++上学习动态编程,这是我的第一个项目(背包问题),请帮助我理解为什么会出现这些错误。

这是我的代码:

代码语言:javascript
运行
复制
#include<bits/stdc++.h>
using namespace std;
#define fastio ios_base::sync_with_stdio(false);cin.tie(0);cout.tie(0);

int knap(int n, int wt[], int price[], int W){          // n = number of items; size of array, w = wt available in knapsack
                                                        // wt stores weight if items, price:price

        // base case
        if(n == 0 || W == 0){
            return 0;
        }
        if(wt[n-1] <= W){           // condition for adding item to knapsack (wt of item must be less than space remaining in knapsack)

            return max((price[n-1] + knap(n-1, wt[], price[], W - wt[n-1])), knap(n-1, wt[], price[], W)) ;  // max wrt recursion from previous element
        }
        else if(wt[n-1] > W){
            return knap(n-1, wt[], price[], W);
        }

}

int main(){
    fastio

    cout<<knap(4, [4, 8, 5, 3], [5, 12, 8, 1], 10);
}

以下是错误:

代码语言:javascript
运行
复制
||=== Build file: "no target" in "no project" (compiler: unknown) ===|
F:\C++\c++\DP\knapsack.cpp||In function 'int knap(int, int*, int*, int)':|
F:\C++\c++\DP\knapsack.cpp|14|error: expected primary-expression before ']' token|
F:\C++\c++\DP\knapsack.cpp|14|error: expected primary-expression before ']' token|
F:\C++\c++\DP\knapsack.cpp|14|error: expected primary-expression before ']' token|
F:\C++\c++\DP\knapsack.cpp|14|error: expected primary-expression before ']' token|
F:\C++\c++\DP\knapsack.cpp|16|error: expected ']' before ')' token|
F:\C++\c++\DP\knapsack.cpp|17|error: expected primary-expression before ']' token|
F:\C++\c++\DP\knapsack.cpp|17|error: expected primary-expression before ']' token|
F:\C++\c++\DP\knapsack.cpp||In function 'int main()':|
F:\C++\c++\DP\knapsack.cpp|25|error: expected identifier before numeric constant|
F:\C++\c++\DP\knapsack.cpp|25|error: expected ']' before ',' token|
F:\C++\c++\DP\knapsack.cpp|25|error: expected '{' before ',' token|
F:\C++\c++\DP\knapsack.cpp||In function 'int main()':|
F:\C++\c++\DP\knapsack.cpp|25|error: expected ')' before ']' token|
||=== Build failed: 11 error(s), 0 warning(s) (0 minute(s), 1 second(s)) ===|

我刚接触c++,刚从python搬到这里,所以如果可能的话,请解释一下。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2021-09-04 06:47:06

替换返回语句

代码语言:javascript
运行
复制
return max((price[n-1] + knap(n-1, wt[], price[], W - wt[n-1])), knap(n-1, wt[], price[], W));

包含以下内容

代码语言:javascript
运行
复制
return max((price[n-1] + knap(n-1, wt, price, W - wt[n-1])), knap(n-1, wt, price, W));

在C++中,当我们将数组传递给函数时,我们只使用数组的名称,而不使用数组的实例……

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/67401506

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档