Open In App

How to Access Elements of a Pair in C++?

Last Updated : 01 Apr, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

In C++, a pair container is defined in <utility> header that can store two values that may be of different data types so as to store two heterogeneous objects as a single unit. In this article, we will learn how to access elements of a pair in C++.

Example:

Input: 
myPair={10,G}

Output:
First Element of Pair: 10
Second Element of Pair: G

Accessing Elements of a Pair in C++

In a std::pair, both key and value are stored as the public data members with the name first and second. To access the elements, we can use the pair name followed by the dot operator followed by the keyword first or second depending on which element we want to access.

Syntax to Access Elements of a Pair in C++

pairName.first   //to access first element of a pair
pairName.second   // to access second element of a pair

C++ Program to Access Elements of a Pair

The below program demonstrates how we can access elements of a pair in C++.

C++
// C++ program to demonstrate how we can access elements of
// a pair
#include <iostream>
#include <utility>
using namespace std;

int main()
{
    // Declare and initialize a pair.
    pair<int, char> p = make_pair(10, 'G');

    // Accessing elements using .first and .second
    cout << "First element: " << p.first << endl;
    cout << "Second element: " << p.second << endl;

    return 0;
}

Output
First element: 10
Second element: G

Time Complexity: O(1)
Auxilliary Space: O(1)




Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads