C++ / CHAPTER 07
Algorithms and comparison contracts
IntermediateSort and summarize collections with reusable standard algorithms.
By the end of this chapter
- Use half-open iterator ranges
- Write a strict sorting comparison
- Separate mutation from observation
The idea
Bring familiarity with vectors and loops. Standard algorithms let you state an operation without rewriting its traversal. A range described by begin and end includes the first element and excludes the end marker. sort rearranges the supplied range; count_if observes it and counts matches. The algorithm name tells you whether order or content can change, which helps callers reason about shared data.
A custom comparison must describe a strict ordering. For ordinary ascending numbers use less-than, not less-than-or-equal: an element must not be considered less than itself. When sorting records, make tie handling explicit if later output depends on it. A lambda can capture a threshold for a predicate, but captures do not automatically make external state safe to mutate during every possible algorithm.
#include <algorithm>
#include <iostream>
#include <vector>
int main(){std::vector<int> a{8,3,5}; std::sort(a.begin(),a.end());
auto n=std::count_if(a.begin(),a.end(),[](int x){return x>=5;});
std::cout<<a.front()<<" "<<a.back()<<" "<<n<<"\n";}3 8 2
Sorting changes the vector to 3, 5, 8. The predicate counts 5 and 8 without removing any elements.
Try it yourself
Sort records by increasing priority, then by name for equal priorities.
Use your own editor for this exercise. Runnable challenges on CodeQuest are available for JavaScript, Python, and SQL.
CHECK YOUR UNDERSTANDING