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
std::sort(first, last)sorts that range in ascending order, in place. It's O(n log n), much faster than a hand-written bubble sort.std::reverse(first, last)flips the range. It works on strings too, because a string is a container of chars.std::max_elementandstd::min_elementreturn an iterator, not a value. Use*itfor the value andit - v.begin()for the index.- The range doesn't have to be the whole container.
temps.begin() + 3stops after three elements, so the last example only sorts the first three, in descending order withstd::greater<int>().
Common mistakes
- Passing iterators from two different containers, like
std::sort(a.begin(), b.end()). That's undefined behavior. - Forgetting that
max_elementon an empty range returnsend(), which you must not dereference.
Your turn: sort the scores ascending, then reverse them so the best is first.