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

This article provides a solution to the Tideman CS50 C++ Sort function. The Tideman Sort function is a sorting algorithm used to sort a list of elements in order of preference. It is a variation of the bubble sort algorithm and is used to rank candidates in an election. This article provides a step-by-step guide to implementing the Tideman Sort function in C++. It also provides an example of the code and a discussion of the algorithm’s complexity.

The following code should do the trick:

#include
#include

using namespace std;

// Function to sort the pairs vector in ascending order
void sortPairs(vector> &pairs)
{
sort(pairs.begin(), pairs.end(), [](const pair &a, const pair &b) {
return a.first < b.first; }); } [ad_1]

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.