What is a C++ pair?

A pair in C++ is a container that stores two values (like a tuple). These values may or may not be of the same data-type.

The declaration involves a keyword (pair) followed by comma-separated data-types within < > signs and the name of the pair.

The elements of a pair can be accessed via the first and second keywords.

svg viewer

Code

#include <iostream>
using namespace std;
int main() {
pair<int, string> anon_pair; // Declaring a pair
anon_pair.first = 17; // Accessing the first element
anon_pair.second = "seventeen"; // Accessing the second element
}

Alternatively, pairs can also be initialized in the following two ways:

#include <iostream>
using namespace std;
int main() {
pair<int, string> pair_1(4, "four"); // 1) Declaring and initializing together
pair<int, string> pair_2; // 2) Declaring
pair_2 = make_pair(5, "five"); //Then initializing using a built-in make_pair function.
}

Operators

  1. The assignment (=) operator lets us assign the values of one pair to another.
  2. The equality (==) operator returns true if two pairs contain the same values. The inequality (!=) operator returns true if two pairs do not contain the same values.
  3. The less-than (<) and greater-than (>) operators work by only comparing the first values of the pairs being compared. The same can be said about the <= and >= operators.

How one can use these operators​ is demonstrated below:

#include <iostream>
using namespace std;
int main() {
pair<int, string> pair_1(1, "one");
pair<int, string> pair_2;
pair_2 = make_pair(2, "two");
if (pair_1 <= pair_2) // Less-than or equal to
{
pair_1 = pair_2; // Assignment
}
if(pair_1 == pair_2) // Equality
{
cout<<pair_1.first<<" "<<pair_1.second<<endl;
}
}

Free Resources

Copyright ©2025 Educative, Inc. All rights reserved