Structs, Lambdas & Structured Bindings
Learn to use structs for custom data types, lambdas for inline functions, and C++17 structured bindings for cleaner code.
Structs, Lambdas & Structured Bindings
As your solutions grow more complex, you need ways to group data and pass custom behavior. Structs, lambdas, and structured bindings are three tools that keep your competitive programming code clean and expressive.
Structures (Structs) in C++
A struct groups related variables under one name:
struct Point {
int x, y;
};
struct Edge {
int u, v, w;
};
int main() {
Point p = {3, 4};
Edge e = {1, 2, 5};
cout << p.x << " " << p.y << "\n"; // 3 4
cout << e.w << "\n"; // 5
}
Structs with Methods
struct Point {
int x, y;
int manhattanDistance(const Point &other) const {
return abs(x - other.x) + abs(y - other.y);
}
};
Point a = {1, 2};
Point b = {4, 6};
cout << a.manhattanDistance(b); // 7
Struct Comparison
By default, structs don't support < or ==. Define them explicitly or use a comparator:
struct Point {
int x, y;
};
// For sorting: define operator<
bool operator<(const Point &a, const Point &b) {
if (a.x != b.x) return a.x < b.x;
return a.y < b.y;
}
// Or use a lambda (see below)
Why Use Structs Over Pairs/Tuples
- Readable:
edge.uis clearer thanget<0>(edge) - Extensible: add methods, constructors, operators
- Type-safe: can't accidentally mix up fields
Lambdas & Inline Comparators
A lambda is an anonymous function — a block of code you can pass around:
auto greet = [](string name) {
cout << "Hello, " << name << "\n";
};
greet("World"); // Hello, World
Lambda Syntax
[capture](parameters) -> return_type { body }
- Capture: variables from the enclosing scope the lambda can access
- Parameters: like function parameters
- Return type: optional (usually deduced)
int x = 10;
auto add = [x](int y) { return x + y; }; // captures x by value
auto increment = [&x](int y) { x += y; }; // captures x by reference
Capture Modes
| Mode | Meaning |
|---|---|
[x] | capture x by value (copy) |
[&x] | capture x by reference |
[] | capture nothing |
[=] | capture all by value |
[&] | capture all by reference |
Lambdas for Custom Sorting
vector<int> a = {3, 1, 4, 1, 5};
// Sort in descending order
sort(a.begin(), a.end(), [](int x, int y) {
return x > y;
});
// Sort pairs by second element
vector<pair<int,int>> v = {{1,3}, {2,1}, {3,2}};
sort(v.begin(), v.end(), [](const pair<int,int> &a, const pair<int,int> &b) {
return a.second < b.second;
});
Lambdas in Priority Queues
// Min-heap (default is max-heap)
priority_queue<int, vector<int>, greater<int>> pq;
// Custom comparator for a struct
struct Edge { int u, v, w; };
auto cmp = [](const Edge &a, const Edge &b) {
return a.w > b.w; // min-heap by weight
};
priority_queue<Edge, vector<Edge>, decltype(cmp)> pq(cmp);
auto & Structured Bindings (C++17)
auto
The auto keyword lets the compiler deduce the type:
auto x = 42; // int
auto pi = 3.14; // double
auto s = "hello"; // const char*
auto v = vector<int>{1, 2, 3}; // vector<int>
Use auto when the type is obvious or when the type is long and cumbersome.
Structured Bindings
C++17 lets you unpack pairs, tuples, and structs directly:
// With pairs
auto [key, value] = make_pair(1, "one");
// With tuples
auto [x, y, z] = make_tuple(1, 2.0, 'a');
// With arrays
int arr[] = {10, 20, 30};
auto [a, b, c] = arr;
// With structs (C++17)
struct Point { int x, y; };
Point p = {3, 4};
auto [px, py] = p; // px = 3, py = 4
Why Structured Bindings Matter
They eliminate boilerplate when iterating over containers:
map<string, int> ages = {{"Alice", 25}, {"Bob", 30}};
// Before C++17
for (const auto &pair : ages) {
cout << pair.first << ": " << pair.second << "\n";
}
// With structured bindings
for (const auto &[name, age] : ages) {
cout << name << ": " << age << "\n";
}
Summary
structgroups related data; add methods withconstmember functions- Lambdas:
[capture](params) { body }— use for inline comparators and callbacks [=]captures by value,[&]captures by referenceautodeduces types; structured bindings[a, b]unpack pairs/tuples/structs- These tools together make C++ code expressive without sacrificing performance
Prefer reading offline? Download the full book as a PDF.
Download Free Book