Dudeness
Dudeness

Reputation: 95

Expected primary-expression before '[' token .. and more

I've been trying to learn dynamic programming on c++, and this is my first project on that (knapsack problem) Please help me understand why I'm getting these errors.

This is my code:

#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);
}

These are the errors:

||=== 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)) ===|

I'm new to c++, just moving here from python, so if possible, please explain with that in consideration.

Upvotes: 0

Views: 986

Answers (1)

parzeval l
parzeval l

Reputation: 26

Replace the return statement

return max((price[n-1] + knap(n-1, wt[], price[], W - wt[n-1])), knap(n-1, wt[], price[], W));

with the following

return max((price[n-1] + knap(n-1, wt, price, W - wt[n-1])), knap(n-1, wt, price, W));

In C++ when we are passing an array to the function we use only the name of the array not the instance of the array...

Upvotes: 1

Related Questions