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.
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::pairholds **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).
| Idea | Meaning |
|---|---|
pair | Two typed fields together |
first / second | Access the two members |
| Heterogeneous | Types of first and second may differ |
| Value type | Copyable/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/multimapstore elements aspair.- Algorithms often work with pairs (e.g. coordinates, scored items).
| Benefit | Example |
|---|---|
| Two return values | pair |
| Key + value | pair |
| Coordinates | pair |
| 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.
| Feature | Pair (std::pair) | Tuple (std::tuple) |
|---|---|---|
| Number of elements | Exactly **2** | Any count (0, 1, 2, …) |
| Access | p.first, p.second | get<0>(t), get<1>(t), … |
| Header | | |
| Create helpers | make_pair, braces | make_tuple, forward_as_tuple |
| Structured bindings | auto [a,b] = p; | auto [a,b,c] = t; |
| Named fields | first / second (fixed names) | No names — index only |
| Common in | map, simple returns | Multi-return, tie unpack |
| Comparison | Lexicographic on first, then second | Lexicographic element-wise |
| When to prefer | Always two related values | Three or more values |
| Readability | Very clear for 2 fields | Better than nested pairs |
Creating a pair
- Direct construction, braced init, or
make_pair. make_paircan deduce types (template argument deduction).- C++17 often prefers
pair{a, b}or structured bindings over oldmake_pairstyle.
#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.firstandp.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/seconddirectly (unless const, as in map keys). swap(p1, p2)orp1.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**:
firstfirst, thensecond. - 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
mapstorespair— iterate withp.first/p.second.vectoris 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:
firstandsecond. - 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).
Advanced — pair
Returning pairs from functions
- Cleaner than out-parameters for two results.
- Often
pairfor success + value, or useoptionalin 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
firstandsecondin place from argument tuples. - Seen when emplacing into maps with non-copyable types.
pair as a map node view
- When iterating a
map,e.firstis the **const** key;e.secondis the mapped value. - You cannot reassign
e.first; change values viae.secondorm[k].
Nested pairs vs tuple
pairworks but is hard to read.> - Prefer
tupleor a smallstructfor 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
vectorfor online judges / ranking problems.> - Do not overuse nested pairs — switch to tuple/struct.
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.
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;
} 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.
Practice Programs List
- Create pair
and print both fields. - Write a function returning pair
of two ints. - Unpack a pair with structured bindings.
- Fill vector
> and sort it. - Iterate a map and print key/value via first/second.
- Demonstrate (1,5) < (1,9) and (1,9) < (2,0).
- Write Pair vs Tuple table in comments (8 rows).
- Swap two pairs and print.
- Store student roll+marks as pairs; find max marks.
- Explain when you would use a struct instead of pair.
- Use get<0> and get<1> on a pair.
- Build edges as vector
> for a tiny graph.