In C++, pair is part of the C++ Standard Template Library and is used to store two values together as a single unit.

Think of it like a small container that always holds exactly two elements.


Basic Syntax

#include <iostream>
#include <utility>  // for pair

using namespace std;

int main() {
    pair<int, int> p;

    p.first = 10;
    p.second = 20;

    cout << p.first << " " << p.second;
}

Output:

10 20

Mental Model

Instead of thinking “pair is a data structure,” think:

"Whenever I need to return or store two related values together, I use pair."

Examples:


Shortcut Initialization

pair<int, int> p = {1, 2};

Or using make_pair: