Skip to main content

C++ STL

pair

Complete lesson for pair using LEARNCODEGURU’s 6-level learning model — from basics to advanced practice, with C++ OOP and STL where relevant.

L1

Basics — pair

Section: C++ STL. C++ std::pair — store two related values, use with maps/algorithms, and Pair vs Tuple.

What is a pair?

  • std::pair holds **two values**, possibly of different types.
  • Members are public: **first** and **second**.
  • Header: #include (also pulled in by , , …).
  • Used everywhere: map elements, return two results, sort by key+value.
  • **Real-life:** a labeled suitcase — name tag (first) + contents (second).
IdeaMeaning
pairTwo typed fields together
first / secondAccess the two members
HeterogeneousTypes of first and second may differ
Value typeCopyable/movable like its members

Why use pair?

  • Return **two** results from a function without a custom struct.
  • Store key–value style data before or outside a full map.
  • map / multimap store elements as pair.
  • Algorithms often work with pairs (e.g. coordinates, scored items).
BenefitExample
Two return valuespair find(...)
Key + valuepair score
Coordinatespair point
Map elements*m.begin() is a pair

Differences between Pair and Tuple

  • Both group values of mixed types — **pair** is fixed at two; **tuple** is N values.
FeaturePair (std::pair)Tuple (std::tuple)
Number of elementsExactly **2**Any count (0, 1, 2, …)
Accessp.first, p.secondget<0>(t), get<1>(t), …
Header
Create helpersmake_pair, bracesmake_tuple, forward_as_tuple
Structured bindingsauto [a,b] = p;auto [a,b,c] = t;
Named fieldsfirst / second (fixed names)No names — index only
Common inmap, simple returnsMulti-return, tie unpack
ComparisonLexicographic on first, then secondLexicographic element-wise
When to preferAlways two related valuesThree or more values
ReadabilityVery clear for 2 fieldsBetter than nested pairs

Creating a pair

  • Direct construction, braced init, or make_pair.
  • make_pair can deduce types (template argument deduction).
  • C++17 often prefers pair{a, b} or structured bindings over old make_pair style.
#include <iostream>
#include <string>
#include <utility>
using namespace std;

int main() {
    pair<string, int> a("age", 21);
    pair<string, int> b = {"score", 99};
    auto c = make_pair(3.5, 'A');

    cout << a.first << " " << a.second << "\n";
    cout << b.first << " " << b.second << "\n";
    cout << c.first << " " << c.second << "\n";
    return 0;
}

Access and structured bindings

  • Classic: p.first and p.second.
  • C++17: auto [x, y] = p; unpacks into named locals.
  • Also: get<0>(p) / get<1>(p) work on pair (tuple-like protocol).
#include <iostream>
#include <string>
#include <utility>
using namespace std;

int main() {
    pair<string, int> p = {"Ann", 20};
    cout << p.first << " " << p.second << "\n";

    auto [name, age] = p;
    cout << name << " is " << age << "\n";
    return 0;
}

Updating and swapping

  • Assign first / second directly (unless const, as in map keys).
  • swap(p1, p2) or p1.swap(p2) exchanges contents.
  • Whole-pair assignment copies/moves both members.
#include <iostream>
#include <utility>
using namespace std;

int main() {
    pair<int, int> a{1, 2}, b{3, 4};
    a.second = 99;
    swap(a, b);
    cout << a.first << "," << a.second << "\n";
    return 0;
}

Comparison of pairs

  • Relational operators compare **lexicographically**: first first, then second.
  • Useful as map/set keys and for sorting vector>.
#include <iostream>
#include <utility>
using namespace std;

int main() {
    pair<int, int> a{1, 5}, b{1, 9}, c{2, 0};
    cout << (a < b) << "\n"; // 1 — same first, 5 < 9
    cout << (b < c) << "\n"; // 1 — 1 < 2
    return 0;
}

pair with map and vectors

  • map stores pair — iterate with p.first / p.second.
  • vector> is a common lightweight “list of records”.
  • Sort pairs to order by key, then value.
#include <iostream>
#include <map>
#include <string>
#include <vector>
#include <algorithm>
using namespace std;

int main() {
    map<string, int> m{{"A", 10}, {"B", 20}};
    for (auto& [k, v] : m) cout << k << ":" << v << "\n";

    vector<pair<int, string>> v = {{2, "b"}, {1, "a"}};
    sort(v.begin(), v.end());
    for (auto& p : v) cout << p.first << p.second << " ";
    cout << "\n";
    return 0;
}

Key points to remember

  • pair = exactly two values: first and second.
  • Prefer pair for two fields; tuple for three or more.
  • map elements are pairs; structured bindings unpack cleanly.
  • Comparisons are lexicographic.
  • Header (or via map/algorithm).
L2

Advanced — pair

Returning pairs from functions

  • Cleaner than out-parameters for two results.
  • Often pair for success + value, or use optional in modern code.
#include <iostream>
#include <utility>
using namespace std;

pair<bool, int> parsePositive(int x) {
    if (x <= 0) return {false, 0};
    return {true, x};
}

int main() {
    auto [ok, n] = parsePositive(5);
    if (ok) cout << n << "\n";
    return 0;
}

piecewise_construct (overview)

  • Advanced: construct first and second in place from argument tuples.
  • Seen when emplacing into maps with non-copyable types.

pair as a map node view

  • When iterating a map, e.first is the **const** key; e.second is the mapped value.
  • You cannot reassign e.first; change values via e.second or m[k].

Nested pairs vs tuple

  • pair> works but is hard to read.
  • Prefer tuple or a small struct for clarity.

Design tips

  • If fields need meaningful names (name, age), prefer a **struct**.
  • Use pair when the two roles are obvious (key/value, x/y, ok/value).
  • Sort vector> for online judges / ranking problems.
  • Do not overuse nested pairs — switch to tuple/struct.
L3

Tricky Interview Points

Q1) What is std::pair?

Answer A template class that stores two values (possibly different types) as public members first and second.

Q2) Pair vs tuple?

Answer pair always holds two elements with first/second; tuple holds any number accessed by get<i> or structured bindings.

Q3) How do you create a pair?

Answer pair<T1,T2> p(a,b); braced init; or make_pair(a,b).

Q4) How does pair comparison work?

Answer Lexicographically: compare first; if equal, compare second.

Q5) How is pair related to map?

Answer map elements are pair<const Key, T>; iteration yields those pairs.

Q6) What are structured bindings for a pair?

Answer C++17 auto [a,b] = p; unpacks first and second into a and b.

Q7) Header for std::pair?

Answer <utility> (also available through many other standard headers).

Q8) When prefer a struct over pair?

Answer When fields need clear names or invariants; pair is best for anonymous two-field bundles.

Q9) Can pair types differ?

Answer Yes — pair<string, int> is common.

Q10) How do you swap two pairs?

Answer std::swap(p1, p2) or p1.swap(p2).

Q11) get<0>(p) on a pair?

Answer Yes — pair supports the tuple-like get interface; get<0> is first, get<1> is second.

Q12) Typical interview use of vector of pairs?

Answer Store edges (u,v), scores (value, id), or intervals; sort lexicographically.

L4

Simple Programs

Create and print a pair

#include <iostream>
#include <string>
#include <utility>
using namespace std;

int main() {
    pair<string, int> p = {"Ann", 20};
    cout << p.first << " " << p.second << "\n";
    return 0;
}

make_pair and structured bindings

#include <iostream>
#include <utility>
using namespace std;

int main() {
    auto p = make_pair(10, 3.14);
    auto [a, b] = p;
    cout << a << " " << b << "\n";
    return 0;
}

Return two values

#include <iostream>
#include <utility>
using namespace std;

pair<int, int> minMax(int x, int y) {
    if (x < y) return {x, y};
    return {y, x};
}

int main() {
    auto [lo, hi] = minMax(8, 3);
    cout << lo << " " << hi << "\n";
    return 0;
}

Sort vector of pairs

#include <iostream>
#include <vector>
#include <utility>
#include <algorithm>
using namespace std;

int main() {
    vector<pair<int, string>> v = {{2, "B"}, {1, "A"}, {2, "A"}};
    sort(v.begin(), v.end());
    for (auto& p : v) cout << p.first << p.second << " ";
    cout << "\n";
    return 0;
}

Iterate map as pairs

#include <iostream>
#include <map>
#include <string>
using namespace std;

int main() {
    map<string, int> m{{"x", 1}, {"y", 2}};
    for (const pair<const string, int>& e : m)
        cout << e.first << "->" << e.second << "\n";
    return 0;
}

pair comparison

#include <iostream>
#include <utility>
using namespace std;

int main() {
    pair<int, int> a{1, 10}, b{1, 5};
    cout << boolalpha << (a > b) << "\n"; // true
    return 0;
}
L5

Problem Solving Tricks

  • pair = first + second (exactly two values).
  • Header ; also comes with map.
  • make_pair or braced init to create.
  • auto [a,b] = p; unpacks in C++17.
  • Comparisons: first, then second.
  • map nodes are pair.
  • Prefer tuple/struct if you need 3+ fields.
  • Sort vector> for ranking problems.
  • get<0>(p) / get<1>(p) also work.
  • Do not nest pairs deeply — readability dies.
  • Use struct when names matter (name/age).
  • Pair vs Tuple table is a common interview ask.
L6

Practice Programs List

  1. Create pair and print both fields.
  2. Write a function returning pair of two ints.
  3. Unpack a pair with structured bindings.
  4. Fill vector> and sort it.
  5. Iterate a map and print key/value via first/second.
  6. Demonstrate (1,5) < (1,9) and (1,9) < (2,0).
  7. Write Pair vs Tuple table in comments (8 rows).
  8. Swap two pairs and print.
  9. Store student roll+marks as pairs; find max marks.
  10. Explain when you would use a struct instead of pair.
  11. Use get<0> and get<1> on a pair.
  12. Build edges as vector> for a tiny graph.