2

I have class called Racecar, and 40 Racecar objects are in a vector and each object has a data member named myTotalPoints.

After each race and points are awarded, I want to sort all of the objects' myTotalPoints data members from greatest to least so I can show them in point standings. Does anyone know how I could sort all 40 of the Racecar objects' data members ?

seaotternerd
  • 6,298
  • 2
  • 47
  • 58

3 Answers3

4

You can use std::sort to solve this problem.

Implement a binary function to be the second parameter in the sort function, and in the binary function return the value basing on the comparison between the values of myTotalPoints in two Racecar Objects.

As the instruction goes, comp is:

Binary function that accepts two elements in the range as arguments, and returns a value convertible to bool. The value returned indicates whether the element passed as first argument is considered to go before the second in the specific strict weak ordering it defines. The function shall not modify any of its arguments. This can either be a function pointer or a function object.

albusshin
  • 3,930
  • 3
  • 29
  • 57
3

The simplest and most concise way is using std::sort() with a C++11 lambda:

std::sort(std::begin(racecars), std::end(racecars),
    [](Racecar const& a, Racecar const& b) {
    return b.myTotalPoints < a.myTotalPoints;   
    });

See an example run!

Community
  • 1
  • 1
johnsyweb
  • 136,902
  • 23
  • 188
  • 247
1

If you want to sort your vector in reverse order, use the reverse iterators.

std::sort(racecars.rbegin(), racecars.rend());

This will work if you have overloaded operator<.

struct Racecar {
    int totalPoints;
    friend bool operator<(const Racecar& left, const Racecar& right);
};

bool operator<(const Racecar& left, const Racecar& right) {
    return left.totalPoints < right.totalPoints;
}

int main()
{
    std::vector<Racecar> cars;
    for (int i = 0; i < 20; i++)
        cars.push_back(Racecar{i});
    std::random_shuffle(cars.begin(), cars.end());
    std::sort(cars.rbegin(), cars.rend());
}