STL Algorithms & Lambdas¶
The STL algorithms library <algorithm> is a collection of powerful, reusable functions that operate on ranges of elements. They decouple what you want to do from how it is done.
Common Algorithms¶
Sorting and Searching¶
Modifying Sequences¶
Non-Modifying Operations¶
Lambda Expressions¶
Lambdas are anonymous functions defined in-place. They are essential for using STL algorithms effectively.
Syntax¶
Captures¶
[]: No captures.[=]: Capture all local variables by value (copy).[&]: Capture all local variables by reference.[x, &y]: Capturexby value,yby reference.
Mutable Lambdas¶
By default, value captures are read-only. Use mutable to modify them (this modifies the lambda's copy, not the original).
C++20 Ranges¶
Ranges simplify the usage of algorithms by allowing you to pass the container directly, rather than begin() and end(). They also support piping.
Best Practices¶
- Prefer Algorithms over Loops: Algorithms are named after what they do (
find,sort,count), making code more readable and less error-prone. - Use Ranges (C++20): They are safer and more composable.
- Be Careful with Captures: Capturing pointers or references in lambdas that outlive the scope leads to dangling references.