Information about cookies on this page

Our website uses cookies to ensure the functionality of the website, to collect and analyze information about the performance and usage of the website. Privacy Policy

  • Courses
    • Discord
    • Twitter
    • Linkedin
    • Facebook
    • Instagram
  • Pricing
  • English
  • Čeština
  • Deutsch
  • Русский
Sign inStart free
  • Courses
  • Pricing

Community

Sign in
  
  • Courses
    • Discord
    • Twitter
    • Linkedin
    • Facebook
    • Instagram
  • Pricing
  • English
  • Čeština
  • Deutsch
  • Русский
Sign inStart free
  • Courses
  • Pricing

Community

Sign in

A Comparison Function

Now let's sort the monsters of our game, with the struct Monster from the lesson on structs. The call that sorted the numbers doesn't compile here:

std::vector<Monster> monsters = {
    {"Goblin", 30, 5},
    {"Troll", 80, 7},
    {"Bat", 8, 2},
};
std::sort(monsters.begin(), monsters.end());

The error message starts with several lines In file included from …, because the mistake shows up inside the library. The line with error says what's wrong:

/usr/include/c++/v1/__algorithm/comp.h:42:18: error: invalid operands to binary expression ('const Monster' and 'const Monster')

std::sort compares the elements with <, and C++ doesn't know what < means for two monsters. By name? By health? By attack? You have to tell it, with a comparison function. It takes two elements and returns true when the first one should come before the second one:

#include <iostream>
#include <algorithm>
#include <string>
#include <vector>

struct Monster {
    std::string name;
    int health;
    int attack;
};

// The monster with the higher attack comes first
bool stronger(const Monster& a, const Monster& b) {
    return a.attack > b.attack;
}

int main() {
    std::vector<Monster> monsters = {
        {"Goblin", 30, 5},
        {"Troll", 80, 7},
        {"Bat", 8, 2},
        {"Orc", 50, 9},
    };
    std::sort(monsters.begin(), monsters.end(), stronger);

    for (const Monster& monster : monsters) {
        std::cout << monster.name << " " << monster.attack << std::endl;
    }
    return 0;
}

This prints:

Orc 9
Troll 7
Goblin 5
Bat 2

The function is the third argument of std::sort. You don't call it yourself: you pass its name, without parentheses, and std::sort calls it many times, always with two monsters, until the whole vector is in order. With parentheses, stronger(), you would call the function right there, with no arguments, and compiling ends with the error no matching function for call to 'stronger'.

The comparison decides the order. a.attack > b.attack puts the higher attack first, so the vector starts with the strongest monster. With a.attack < b.attack, it would start with the weakest. And instead of attack, you can compare any other member.

Two more rules:

  • For two equal elements, the function must return false, because neither of them comes before the other. So compare with > or <, never with >= or <=. With >=, std::sort can get lost: here, sorting a vector of 100 equal numbers that way stops the program with the error RuntimeError: memory access out of bounds.
  • Elements that the function considers equal can end up in any order. std::sort doesn't promise to keep them as they were.

Instructions

  1. 1

    In place of the comment, write a comparison function lessHealth that takes two monsters as const references and returns true when the first one has less health than the second one. Use it to sort monsters before they are printed. The list under By health: then starts with Bat: health 8, attack 2 and ends with Troll: health 80, attack 7. Keep the monsters in the vector as they are: the exercise also runs your program with other values.

  2. 2

    Below lessHealth, write a second comparison function, higherAttack, which puts the monster with the higher attack first. At the end of main (before return 0;), print By attack:, sort monsters with higherAttack and print them again with printMonsters. The new list starts with Orc: health 50, attack 9 and ends with Slime: health 15, attack 1.

Back

3/13

  1. 1. Sorting: std::sort
  2. 2. Reversing: std::reverse
  3. 3. A Comparison Function
  4. 4. Lambdas
  5. 5. Quiz: Sort Order
  6. 6. Counting: std::count_if
  7. 7. Capturing Variables
  8. 8. Searching: std::find
  9. 9. Searching with a Lambda: std::find_if
  10. 10. Quiz: Searching
  11. 11. The Largest Element: std::max_element
  12. 12. Yes or No: std::any_of and std::all_of
  13. 13. Summary
Next

Try it yourself

Do this exercise right here in your browser. No account needed.