简体   繁体   中英

C++ Why Does Accessing Elements in an Array Return a Pointer?

My comfort language is Java, but recently I decided to learn C++ syntax.

int ks(int Wt[], int Va[], int N, int totW){

if(N==0){
    return 0;
}

int V[N+1][totW+1];

for(int i = 0; i < N+1; i++){
    V[i][0] = 0; // fill first row with 0's
}
for(int i = 0; i < totW+1; i++){
    V[0][i] = 0; // fill first column with 0's
}

for(int i = 1; i < N+1; i++){
    for(int j = 0; j < totW+1; j++){
        if(Wt[i] <= j) {
            V[i][j] = std::max(V[i-1][j], Va[i]+V[i-1, j- Wt[i]]);
        } else {
            V[i][j] = V[i-1][j];
        }
    }
}
return V[N][totW];
}

This is my implementation of 01 knapsack. However, I get an error in the line:

V[i][j] = std::max(V[i-1][j], Va[i]+V[i-1, j- Wt[i]]);

The error reads:

no instance of overloaded function "std::max" matches the argument list -- argument types are: (int, int *)

My question is, why does Va[i] return a pointer whereas V[i-1][j] doesn't?

V[i-1, j- Wt[i]] is not how you access a two-dimensional array in C++. In fact, there is no such thing as a primitive two-dimensional array, only arrays of arrays (that's what V is). You always need to access them with several consecutive [] .

The , in that expression (and in other expressions where it does not mean something else) is the comma operator that evaluates and then discards its left operand. So what your code tries to do is:

  1. Calculate i-1 , then discard the result.
  2. Calculate j-Wt[i] and then access V[j-Wt[i]] . That's not what you wanted.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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