[Solved] Tideman CS50 C++ Sort function [closed]


This is taking the pairs by value:

void swap (pair a, pair b)     // a is a copy of pairs[i] and b is a copy of pairs[j]

The change you make to a and b inside the function will be discarded when the function exits. a and b are local to the function only.

Take them by reference (pair&) instead and then swap the correct variables:

void swap (pair& a, pair& b) { // a is a ref to pairs[i] and b is a ref to pairs[j]
     pair temp = a;            // temp is copy constructed from pairs[i]
     a = b;                    // pairs[i] is copy assigned from pairs[j]
     b = temp;                 // pairs[j] is copy assigned from temp
}

Sidenote: There’s an excellent swap utility in the standard library called std::swap

In your sum function, there is a, b and what can be seen as an unnamed temporary variable involved. It’s the return value. It’ll maybe be clearer if I show it by adding it:

int sum (int a, int b) {
    int temp = a + b;
    return temp;
}

No changes are done to a and b and you return the result of the calculation. In the swap function, you are supposed to change the variables used as input which is why you need to use references to those variables. You could for example write another add-function like this:

void add_x_to_y(int x, int& y) {
    y += x;
}

Here x is taken by value and y by reference, because we’re supposed to add x to y. The change made to y inside the function will then be made directly to the variable passed to the function as y.

what confuse me the most is when do we need to use a pointer.

In no case here is a pointer used. Only references and values.

21

solved Tideman CS50 C++ Sort function [closed]