R.4 — algorithm functions
Read one box at a time. No rush.
All need #include <algorithm>.
| Code | What it does |
|---|---|
std::sort(v.begin(), v.end()) | sort small → big |
std::sort(v.begin(), v.end(), std::greater{}) | sort big → small |
std::reverse(v.begin(), v.end()) | reverse |
std::find(v.begin(), v.end(), x) | find x (compare with v.end()) |
std::count(v.begin(), v.end(), x) | how many times x appears |
std::count_if(b, e, test) | how many pass a test |
std::max_element(b, e) / std::min_element(b, e) | biggest / smallest (gives an iterator; use *) |
std::max(a, b) / std::min(a, b) | bigger / smaller of two |
std::swap(a, b) | swap two values |
std::accumulate(b, e, 0) | add them all up (<numeric>) |
C++
std::vector<int> v { 4, 1, 3 };std::sort(v.begin(), v.end());int biggest { *std::max_element(v.begin(), v.end()) }; // 4Tip: press ← / → to move between lessons, / to search.