C/C++ Arena

Step 1 of 6

sort and reverse

So far you've written a loop for every job: finding the biggest value, reversing, summing. Those loops are short, but each one is a chance to get an index wrong. The <algorithm> header has ready-made, tested versions of the common ones. Using them makes code shorter and says what it does by name.

Algorithms work on a range given as two iterators: where to start and where to stop (one past the last element). For a whole vector that's v.begin(), v.end().

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

int main() {
    std::vector<int> temps = {18, 25, 12, 30, 21};
    auto hottest = std::max_element(temps.begin(), temps.end());
    std::cout << "max " << *hottest << " at day " << (hottest - temps.begin()) << "\n";

    std::sort(temps.begin(), temps.end());
    for (int t : temps) std::cout << t << " ";
    std::cout << "\n";

    std::string word = "stressed";
    std::reverse(word.begin(), word.end());
    std::cout << word << "\n";

    std::sort(temps.begin(), temps.begin() + 3, std::greater<int>());
    for (int t : temps) std::cout << t << " ";
    std::cout << "\n";
}
max 30 at day 3
12 18 21 25 30 
desserts
21 18 12 25 30 

How it works

Common mistakes

Your turn: sort the scores ascending, then reverse them so the best is first.

Next: Lambdas