>RunTimeFix
BookStudyPracticeInterviewsYouTubeCoursesAbout
Log inGet Started

Table of Contents

01C++ Foundations & Input/Output02Loops & Direct Simulations03Arrays, Strings & Character Operations04Functions & Recursion05Strings & Character Operations06Structs, Lambdas & Structured Bindings07Preprocessor, Debug Macros & Compilation08Vectors, Pairs & Utility Algorithms09Sets, Maps & Multi-Containers10Sorting & Frequency Arrays11Complexity & Problem Solving12Basic Number Theory & Modular Arithmetic13Prefix Sums & Difference Arrays14Two Pointers & Sliding Window15Binary Search (Array & Answer Space)16Greedy Algorithms & Constructive Problems17Bit Manipulation & Masking18Stacks, Queues & Monotonicity19Disjoint Set Union (DSU)20Coordinate Compression, Fenwick Tree & Segment Tree21Graph Representation, DFS & BFS22Cycle Detection, Bipartite Checking & Topological Sort23Dijkstra, 0-1 BFS & Kruskal's MST24Rooted Trees — DFS, Subtree Size & Diameter25Binary Lifting, LCA & Euler Tour26Dynamic Programming — Foundations27Dynamic Programming — Knapsack & Subsets28Backtracking & Meet-in-the-Middle29Modular Inverse, Combinatorics & Fast Math30Hashing, String Algorithms & Geometry Basics
Study Library/Ch 6
Chapter 06 of 30

Structs, Lambdas & Structured Bindings

Learn to use structs for custom data types, lambdas for inline functions, and C++17 structured bindings for cleaner code.

Structures (Structs) in C++Lambdas & Inline Comparatorsauto & Structured Bindings (C++17)
Share:

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:

hljs cpp
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

hljs cpp
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:

hljs cpp
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.u is clearer than get<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:

hljs cpp
auto greet = [](string name) {
    cout << "Hello, " << name << "\n";
};
greet("World");  // Hello, World

Lambda Syntax

code
[capture](parameters) -> return_type { body }
  • Capture: variables from the enclosing scope the lambda can access
  • Parameters: like function parameters
  • Return type: optional (usually deduced)
hljs cpp
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

ModeMeaning
[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

hljs cpp
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

hljs cpp
// 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:

hljs cpp
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:

hljs cpp
// 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:

hljs cpp
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

  • struct groups related data; add methods with const member functions
  • Lambdas: [capture](params) { body } — use for inline comparators and callbacks
  • [=] captures by value, [&] captures by reference
  • auto deduces types; structured bindings [a, b] unpack pairs/tuples/structs
  • These tools together make C++ code expressive without sacrificing performance
Ch 5: Strings & Character OperationsCh 7: Preprocessor, Debug Macros & Compilation

Prefer reading offline? Download the full book as a PDF.

Download Free Book
>RunTimeFix

Practical programming education. Books, videos, courses, and hands-on learning for competitive programming, DSA, and software engineering.

RunTimeFix

  • About
  • YouTube
  • Book
  • Study Library
  • Courses

Learn

  • Competitive Programming
  • DSA
  • Development
  • Databases

Legal

  • Privacy
  • Terms
  • Refund Policy

RunTimeFix — debug → solve → run

© 2026 RunTimeFix. All rights reserved.