Code360 powered by Coding Ninjas X Naukri.com. Code360 powered by Coding Ninjas X Naukri.com
Table of contents
1.
Introduction
2.
What is Pair in C++?
3.
Syntax to Declare a Pair in C++
3.1.
Parameters
3.2.
Example of Pair in C++
3.3.
C++
4.
C++ Pair STL Functions
4.1.
1. make_pair
4.1.1.
Example
4.2.
C++
4.3.
2. swap
4.3.1.
Example
4.4.
C++
4.5.
3. tie()
4.6.
C++
5.
Types of Operators Used in Pair in C++
6.
Nested Pairs
6.1.
C++
7.
Frequently Asked Questions
7.1.
Why is pair in C++ used?
7.2.
What is pair in data structure?
7.3.
What is the use of make pair in C++?
7.4.
What is an example of a function pair?
8.
Conclusion
Last Updated: Mar 27, 2024
Easy

Pair in C++

Author Juhi Sinha
1 upvote
Master Python: Predicting weather forecasts
Speaker
Ashwin Goyal
Product Manager @

Introduction

Pair in c++ is used to combine two elements of the same data types or different data types in C++. Pair is basically used if we want to store tuples and it also provides a way to store two heterogeneous objects as a single unit. 

 In this blog, we will read Pair in C++. So without any further ado, let's get started!  

What is Pair in C++?

In C++, a pair is a container for two values (like a tuple). The datatype of these values might or might not be the same.

The name of the pair is followed by comma-separated data types enclosed in < > signs and the keyword "pair" in the declaration.

The first and second keywords can be used to access the elements of a pair.

Get the tech career you deserve, faster!
Connect with our expert counsellors to understand how to hack your way to success
User rating 4.7/5
1:1 doubt support
95% placement record
Akash Pal
Senior Software Engineer
326% Hike After Job Bootcamp
Himanshu Gusain
Programmer Analyst
32 LPA After Job Bootcamp
After Job
Bootcamp

Syntax to Declare a Pair in C++

In C++, the pair is a container in <utility> header and is also a container class in STL (Standard Template Library) which uses the “std” namespace so it will be as std::pair template class for demonstrating pair as a tuple.

In general, the syntax of pair can be defined as below:

syntax to Declare a Pair in C++

pair(dt1, dt2) pair_name;

Parameters

dt1 The first element's data type.
dt2 The first element's data type.
pair_name It is the name given to the pairs of object.

You can also do a free certification of Basics of C++.

Example of Pair in C++

Let us understand the syntax with the help of the code given below:

  • C++

C++

#include <iostream>
#include <utility>
using namespace std;
int main()
{
pair<int, char> p;
p.first = 25;
p.second = 'A';
cout << p.first << " ";
cout <<p.second << endl;
return 0;
}


Output

25 A

In the programme mentioned above, we can see that we have included the <utility> header for using pair containers, the <iostream> header for printing messages or for input or output, and the namespace is used for using std. Additionally, we have declared the namespace at the beginning. Next, according to the syntax, we can use the pair containers to declare items with the same data type, "int" though we can also use different datatypes.

C++ Pair STL Functions

Function Description Syntax
make_pair() Creates a pair object with two elements. std::make_pair(element1, element2);
swap() Swaps the values of two variables. std::swap(var1, var2);
tie() Creates a tuple of references to variables. std::tie(var1, var2, ...);

1. make_pair

By using the template feature, you can create a value pair in C++ without having to write the forms.

pair_name = make_pair (value_1,value_2);

Example

Let us understand the make_pair member function in C++ with the help of the code given below:

  • C++

C++

#include <iostream>
#include <utility>
using namespace std;
int main()

{

pair <int, char> p1 ;
pair <string, double>p2 ("Ninjas_Coder", 2.55) ;
pair <string, double> p3 ;

p1.first = 25;
p1.second = 'A' ;
p3 = make_pair ("Coding_Ninjas", 5.55);

cout << p1.first << " " ;
cout << p1.second << endl ;
cout << p2.first << " " ;
cout << p2.second << endl ;
cout << p3.first << " " ;
cout << p3.second << endl ;
return 0;
}


Output

25 A
Ninjas_Coder 2.55
Coding_Ninjas 5.55

2. swap

Using this function, one pair object's contents are switched for those of another pair object. Pairs must belong to the same category.

Syntax

pair_1.swap(pair_2); 

The swap function will swap pair_1.first with pair_2.first and pair_1.second with pair_2.second for two given pairs of the same type, pair_1 and pair_2.

Example

Let us understand the swap member function in pair in C++ with the help of the code given below:

  • C++

C++

#include <iostream>
#include<utility>
using namespace std;

int main()
{
pair<char, int>p1 = make_pair('A', 25);
pair<char, int>p2 = make_pair('B', 50);
cout << "Contents of p1 = "
<< p1.first << " " << p1.second << endl ;
cout << "Contents of p2 = "
<< p2.first << " " << p2.second ;

p1.swap(p2);

//After swapping

cout << "Contents of p1 = "

<< p1.first << " " << p1.second << endl ;

cout << "Contents of p2 = "

<< p2.first << " " << p2.second ;

return 0;

}


Output

Contents of p1 = A 25
Contents of p2 = B 50
Contents of p1 = B 50
Contents of p2 = A 25

You can try and compile with the help of online c++ compiler.

3. tie()

The std::tie() function is a utility function in C++ that creates a tuple of lvalue references. It's commonly used in conjunction with std::pair and std::tuple for unpacking values.

The syntax for std::tie() is quite straightforward. It takes any number of arguments, each being a non-const lvalue reference, and returns a tuple of lvalue references to these arguments. Here's the general syntax:

std::tie(var1, var2, ..., varn) = someTupleOrPair;

In this syntax:

  • var1, var2, ..., varn are the variables you want to assign the values to.
  • someTupleOrPair is the tuple or pair you want to unpack

Here is an example of how std::tie can be used:
 

  • C++

C++

#include <iostream>
#include <tuple>
int main() {
std::pair<int, char> p = std::make_pair(1, 'a');

int first;
char second;

std::tie(first, second) = p; // unpacking pair p

std::cout << "first: " << first << ", second: " << second << '\n';

return 0;
}

Types of Operators Used in Pair in C++

Let us learn different types of operators that we use in pair in C++ with the help of a table given below:

Operators Description
Equal(=) It gives a pair of object a new assignment.
Comparison(==) The comparison operator compares the “first value and the second value of those two pairs, i.e. if pair_1.first is equal to pair_2.first or not” and “if pair_1.second is equal to pair_2.second or not” for the two given pairs, pair1 and pair2.
Not equal(!=) The != operator compares the first values of the two pairs, pair_1 and pair_2, to determine whether or not they are equal. If they are, the second values of both pairs are then checked.
Logical(>=,<=) Pairs can also be used with the = and > operators for the two given pairs, pair_1 and pair_2. By only comparing the first value of the pair, it returns either 0 or 1.

Nested Pairs

Nested pairs refer to a data structure where elements are organized in pairs, and these pairs can themselves contain other pairs, forming a nested structure. This nesting can continue to any depth, creating hierarchical relationships between elements. Nested pairs are commonly used in various contexts, including representing hierarchical data, defining tree structures, and implementing complex data structures like nested lists or dictionaries. In C++, nested pairs can be implemented using the std::pair and std::vector containers. Here's an example:

  • C++

C++

#include <iostream>
#include <vector>
#include <utility>

using namespace std;

int main() {
// Nested pairs example
pair<int, int> pair1 = make_pair(1, 2);
pair<int, int> pair2 = make_pair(3, 4);
pair<pair<int, int>, pair<int, int>> nestedPair = make_pair(pair1, pair2);

// Accessing elements
cout << "First element of the outer pair: " << nestedPair.first.first << endl;
cout << "Second element of the inner pair: " << nestedPair.second.second << endl;

return 0;
}

Output

First element of the outer pair: 1
Second element of the inner pair: 4

 

Explanation: In this example, nestedPair is a nested pair containing two pairs of integers. Each pair represents a set of coordinates. The first member of nestedPair contains the first pair (1, 2), and the second member contains the second pair (3, 4). You can access elements of the nested pairs using dot notation or std::get.

Frequently Asked Questions

Why is pair in C++ used?

Pair is a term used to combine two values, which may be of various data types. Pair offers a way to keep two disparate objects together in storage. Essentially, we use it to store tuples.

What is pair in data structure?

In data structures, a pair is a container that holds two values, often of different types, allowing the grouping of two related elements.

What is the use of make pair in C++?

make_pair in C++ is used to create a pair object conveniently by providing two values, which simplifies the process of initializing pairs.

What is an example of a function pair?

An example is std::pair<int, string> myPair = std::make_pair(42, "Hello");, creating a pair of integer and string values.

Conclusion

In this article, we have discussed how to use a pair in C++ along with its various member functions. The pair in C++ proves to be a versatile and essential component for managing pairs of related values. Its simplicity, coupled with functions like make_pair, streamlines data handling. Whether in algorithms or data structures, the pair serves as a powerful tool, enhancing the efficiency and readability of C++ code. 

To learn more about Data Structures and Algorithms, you can enroll in our DSA in C++ Course.

Do upvote our blog to help other ninjas grow.

Happy Coding!

Previous article
Dynamic Binding in C++
Next article
Program to Print Array in C & C++
Live masterclass