Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / C++

std::pair — a pair of two values

std::pair<T1, T2> groups two values, potentially of different types, in one object. Its public first and second data members provide direct access to the first and second elements.

Version: C++23; repository compiler flag, production runtime not attested

Syntax

#include <utility>
std::pair<T1, T2> name{value1, value2};
name.first;
name.second;

std::pair<T1, T2> is a class template from <utility> that groups exactly two elements. T1 and T2 may be the same type or different types. A pair is useful when two values should travel together, such as a player's name and score.

std::pair::first is a public data member of type T1, and std::pair::second is a public data member of type T2. For an object named score, use score.first and score.second, without function-call parentheses. Initialization with {value1, value2} supplies values in that order. Whether an element can be changed depends on its type and the object's qualifiers.

The example creates a std::pair<std::string, int>, increases score.second from 7 to 10, and prints Ada: 10. The displayed code was run unchanged in an isolated environment, and its standard output matched the expected output exactly. The linked standard is an evolving draft, not a frozen C++23 publication; this entry is limited to basic operations available in C++23.

Examples

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

int main() {
    std::pair<std::string, int> score{"Ada", 7};
    score.second += 3;
    std::cout << score.first << ": " << score.second << '\n';
}

Result

Ada: 10

The displayed code and declared result were verified in an isolated environment using the method recorded in the verification evidence for this exact version.

Sources