Summary
In this lesson, you learned that:
- An algorithm is a recipe that solves a task step by step, and the library
<algorithm>has many of them ready-made. They work on a range:v.begin(), v.end()is the whole vector, whereend()is the position after the last element. std::sort(v.begin(), v.end())sorts the vector itself, from the smallest value. Strings go in the order of their character codes.std::reverseturns the order around, and works on a string too.- A comparison function, such as
bool stronger(const Monster& a, const Monster& b), returnstruewhenashould come beforeb. You pass its name tostd::sortwithout parentheses. It compares with<or>, never with<=or>=, and elements that it considers equal can end up in any order. - A lambda is a function without a name, written right where it's needed:
[](const Monster& a, const Monster& b) { return a.attack > b.attack; }. The compiler works out its return type. std::count(v.begin(), v.end(), value)counts the elements equal to a value, andstd::count_ifthe elements for which a lambda with one parameter returnstrue.- A lambda sees only its parameters and its own variables. To use a variable from outside, capture it in the square brackets:
[limit](int score) { return score > limit; }. Several variables are separated by commas. std::find(v.begin(), v.end(), value)andstd::find_ifwith a lambda return an iterator to the first element that fits, orend()when there's none. Checkit != v.end()before you use*it.- An iterator works like a pointer:
*itis the element,it->nameis short for(*it).name, andit - v.begin()is the index. Withauto it, you don't have to write its long type. std::max_elementandstd::min_elementreturn an iterator to the largest and the smallest element. Their lambda says whetherais smaller thanb, so it compares with<.std::max(a, b)andstd::min(a, b)pick one of two values.std::any_of,std::all_ofandstd::none_ofanswer a yes-or-no question about the whole vector.
That covers all the topics of the course. In the next lesson, the Final Project, you will write one bigger program step by step, for a teacher's test results, and use everything you know from the course in it, structs, maps and the algorithms of this lesson included.
Instructions
- 1
Let's practice. The hero fights the monsters from the weakest to the strongest. Sort
monstersby health, lowest first, with a lambda, and print each monster on its own line as its name with its health in parentheses. The list starts withBat (8)and ends withDragon (200). Keep the monsters as they are: the exercise also runs your program with other values. - 2
With one hit, the hero defeats a monster whose health is at most
heroAttack. Below the list, find withstd::find_ifthe first monster in the sorted vector that the hero can't defeat with one hit, and printFirst real fight: Orc. When the hero can defeat every monster with one hit, printEvery fight is easyinstead. Keep the line withheroAttackas it is.