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

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)






Reffered: https://www.geeksforgeeks.org


C++

Related
How to Remove an Element from the End of a List in C++? How to Remove an Element from the End of a List in C++?
How to Find the Size of a Deque in C++? How to Find the Size of a Deque in C++?
How to Check if a Deque is Empty in C++? How to Check if a Deque is Empty in C++?
How to Find Average of All Elements in a Deque in C++? How to Find Average of All Elements in a Deque in C++?
How to Find Last Occurrence of an Element in a Deque in C++? How to Find Last Occurrence of an Element in a Deque in C++?

Type:
Geek
Category:
Coding
Sub Category:
Tutorial
Uploaded by:
Admin
Views:
15