Codiqo

Learn C++ · lesson 28 of 61 · about 8 minutes

Algorithms

Sort the bag, count and sell the gems, and look for the gate key, with the standard algorithms.

What you'll learn

  • Sort with std::sort
  • Search with std::find and count with std::count
  • Total with std::accumulate

Sorting the bag

Before the last gate, the hero tidies the bag: std::sort puts the items in alphabetical order. A trader buys every gem for 15 gold, and std::count says how many there are. The gate needs a key, and std::find looks for one: it gives back bag.end() when there isn't one.

Don't write it yourself

<algorithm> and <numeric> have tested, fast versions of common loops. They work on a range given by v.begin() and v.end():

| Call | Does |
|---|---|
| std::sort(v.begin(), v.end()) | sorts low to high |
| std::find(b, e, x) | iterator to x, or e if missing |
| std::count(b, e, x) | how many equal x |
| std::accumulate(b, e, 0) | the total |
| std::max_element(b, e) | iterator to the biggest |

Algorithms in action

#include <algorithm>
#include <iostream>
#include <numeric>
#include <vector>

int main() {
    std::vector<int> v = {42, 7, 19, 7, 3};
    std::cout << std::accumulate(v.begin(), v.end(), 0) << "\n";
    std::cout << std::count(v.begin(), v.end(), 7) << "\n";
    std::cout << *std::max_element(v.begin(), v.end()) << "\n";
    bool has19 = std::find(v.begin(), v.end(), 19) != v.end();
    std::cout << std::boolalpha << has19 << "\n";
    std::sort(v.begin(), v.end());
    for (int x : v) std::cout << x << " ";
    std::cout << "\n";
    std::sort(v.begin(), v.end(), std::greater<int>());
    std::cout << v.front() << "\n";
}

Output

78
2
42
true
3 7 7 19 42
42

Tip

An iterator is like a pointer to a position in the container. *it gives the item at that position, and v.end() means one past the last item.

Now try it yourself

This lesson is free in Codiqo, with 9 questions on what you just read. You can only learn to code by writing code, so it ends with a short program you write yourself, which we run and check straight away.