Lambdas and Algorithms
<algorithm> provides ready-made operations like std::sort that work on any container's begin()/end() iterator pair, rather than you writing a sorting loop by hand.
main.cpp
Try it yourself →#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
int main() {
vector<int> numbers = {5, 2, 8, 1, 9};
sort(numbers.begin(), numbers.end());
for (int n : numbers) {
cout << n << " ";
}
cout << endl;
return 0;
}Output
1 2 5 8 9
Lambda expressions
A lambda, written [capture](params) { body }, is an anonymous inline function — the [capture] list says which surrounding variables it can see. Combined with an algorithm like std::find_if, a lambda lets you express a custom condition without writing a separate named function just for that one use.
main.cpp
Try it yourself →#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
int main() {
vector<int> numbers = {1, 2, 3, 4, 5};
int threshold = 3;
auto it = find_if(numbers.begin(), numbers.end(), [threshold](int n) {
return n > threshold;
});
if (it != numbers.end()) {
cout << "First number greater than " << threshold << " is " << *it << endl;
}
return 0;
}Output
First number greater than 3 is 4
Next: smart pointers — the modern, RAII-based alternative to manual new and delete.
Practice exercise
Given vector<int> numbers = {1, 2, 3, 4}, build a new vector containing each number squared, then print all of them separated by spaces.