LearnFrenzy
Sign in Take a free test

STL: Set, Map and Hash Tables · Lesson 22 of 33

pair and tuple in C++

5 min read Updated Nov 7, 2026 Saurabh Samir

Often you need to keep two or three values together without defining a whole class: a coordinate, a (score, name) entry, a graph edge (from, to, weight). std::pair holds two values and std::tuple holds any number. They compare lexicographically, which makes sorting by several keys almost free – a favourite trick in competitive programming.

In this lesson

  • Creating and using pairs
  • Comparing and sorting pairs
  • tuples, structured bindings and std::tie
  • When a struct is better

std::pair

#include <iostream>
#include <string>
#include <utility>

int main() {
    std::pair<std::string, int> a{"Asha", 91};
    auto b = std::make_pair(std::string{"Ravi"}, 74);
    std::pair c{3.5, 'x'};                        // types deduced (C++17)

    std::cout << a.first << " scored " << a.second << '\n';
    b.second += 6;
    auto [name, score] = b;                       // structured bindings
    std::cout << name << " scored " << score << '\n';
    std::cout << c.first << ' ' << c.second << '\n';
    return 0;
}

Output

Asha scored 91
Ravi scored 80
3.5 x

Sorting pairs

Pairs compare by first, and by second when the firsts are equal. Choose what goes first to get the order you want:

#include <algorithm>
#include <iostream>
#include <string>
#include <utility>
#include <vector>

int main() {
    std::vector<std::pair<int, std::string>> ranking{
        {88, "Meera"}, {91, "Asha"}, {74, "Ravi"}, {88, "Kiran"}};

    std::sort(ranking.begin(), ranking.end());                       // by score, then name
    for (const auto& [s, n] : ranking) std::cout << s << ' ' << n << " | ";
    std::cout << '\n';

    std::sort(ranking.begin(), ranking.end(), [](const auto& x, const auto& y) {
        if (x.first != y.first) return x.first > y.first;           // score high to low
        return x.second < y.second;                                  // name A to Z
    });
    for (const auto& [s, n] : ranking) std::cout << s << ' ' << n << " | ";
    std::cout << '\n';

    std::vector<std::pair<int, int>> pts{{3, 1}, {1, 2}, {3, 0}, {1, 1}};
    std::sort(pts.begin(), pts.end());
    for (auto [x, y] : pts) std::cout << '(' << x << ',' << y << ") ";
    std::cout << '\n';
    return 0;
}

Output

74 Ravi | 88 Kiran | 88 Meera | 91 Asha | 
91 Asha | 88 Kiran | 88 Meera | 74 Ravi | 
(1,1) (1,2) (3,0) (3,1) 

Contest trick: negate to reverse one key

To sort by score descending and name ascending without a lambda, store {-score, name} and use the default sort. The same trick turns a max-heap into a min-heap in priority_queue (next chapter).

std::tuple and std::tie

#include <algorithm>
#include <iostream>
#include <string>
#include <tuple>
#include <vector>

std::tuple<int, int, double> stats(const std::vector<int>& v) {    // return three values
    auto [lo, hi] = std::minmax_element(v.begin(), v.end());
    double sum = 0;
    for (int x : v) sum += x;
    return {*lo, *hi, sum / v.size()};
}

int main() {
    auto [lo, hi, avg] = stats({72, 95, 41, 88});
    std::cout << lo << ' ' << hi << ' ' << avg << '\n';

    std::tuple<std::string, int, double> edge{"A->B", 7, 2.5};
    std::cout << std::get<0>(edge) << ' ' << std::get<1>(edge) << ' ' << std::get<2>(edge) << '\n';

    int a = 1, b = 2;
    std::tie(a, b) = std::make_tuple(b, a);       // swap via tie
    std::cout << a << ' ' << b << '\n';

    struct Student { std::string name; int marks; int age; };
    std::vector<Student> cls{{"Asha", 88, 21}, {"Ravi", 88, 20}, {"Meera", 91, 22}};
    std::sort(cls.begin(), cls.end(), [](const Student& x, const Student& y) {
        return std::tie(y.marks, x.age) < std::tie(x.marks, y.age);   // marks desc, age asc
    });
    for (const auto& s : cls) std::cout << s.name << ' ';
    std::cout << '\n';
    return 0;
}

Output

41 95 74
A->B 7 2.5
2 1
Meera Ravi Asha 

std::tie builds a tuple of references, so comparing two ties compares several fields in order – a concise way to write multi-key comparators.

pair/tuple or struct?

Use pair/tuple whenUse a struct when
the grouping is local and short-livedthe data is used in many places
you want free lexicographic comparisonfield names make the code clearer (s.marks vs p.second)
returning a couple of valuesthere are more than two or three fields

Practice

Try it yourself

  1. Sort intervals by start time, then merge the overlapping ones.

    Show solution
    #include <algorithm>
    #include <iostream>
    #include <utility>
    #include <vector>
    
    int main() {
        std::vector<std::pair<int, int>> iv{{8, 10}, {1, 3}, {2, 6}, {15, 18}, {9, 12}};
        std::sort(iv.begin(), iv.end());
        std::vector<std::pair<int, int>> merged;
        for (auto [s, e] : iv) {
            if (!merged.empty() && s <= merged.back().second) merged.back().second = std::max(merged.back().second, e);
            else merged.push_back({s, e});
        }
        for (auto [s, e] : merged) std::cout << '[' << s << ',' << e << "] ";
        std::cout << '\n';
        return 0;
    }

    Output

    [1,6] [8,12] [15,18] 

Quick check

How do two pairs compare?

By first; if equal, by second (lexicographic).

How do you read the third element of a tuple t?

std::get<2>(t), or structured bindings.

What does std::tie(a, b) create?

A tuple of references to a and b.

Summary

  • pair holds two values, tuple any number; unpack both with structured bindings.
  • They compare lexicographically, so sorting by several keys is easy (negate to reverse one).
  • std::tie writes multi-field comparisons; prefer a struct when names matter.

Finished this lesson?

Mark it complete to track your progress, then carry on with the next lesson.

Next lesson

Search LearnFrenzy

Esc

Quick links