Working with Pairs in C++

Working with Pairs in C++

5 mins read587 Views Comment
clickHere
Updated on Oct 11, 2023 17:13 IST

In this article, we will learn what are pairs in C++, and how to initialize pairs in C++. Some common C++pairs STL functions. Later in the article, we will also discuss some examples to get a better understanding of pairs in C++.

2023_02_MicrosoftTeams-image-170.jpg

The C++ pair is similar to a Python tuple and consists of two elements, “first” and “second”, in a fixed order. The “first” element is the first element in the pair, and the “second” element is the second. The header file for the pair in C++ is located in the <utility> header and it is also a container class in the Standard Template Library (STL). In this tutorial, we will go in-depth into the representation and implementation of pairs in C++. So, without further ado, let’s get started!

Table of Content

What are Pairs in C++?

The C++ pair container is a simple header file that holds two distinct elements or objects in a specific order. The first element is referred to as “first” and the second element is referred to as “second.” This container allows for the storage of two values as a single entity, making it easier to access and manipulate the values. The values stored in a pair can be of different or the same data types. By default, pair objects are used in maps or HashMap as the default list type, where the “first” component serves as a unique key for the “second” component.

Must Read: What is C++?

Must Check: C++ Online Courses and Certifications

Syntax

pair <dtype1, dtype2> pair_name;

The parameters are:

  • dtype1 : data type of the first element.
  • dtype2 : data type of the second element.

How to Initialize Pairs in C++?

There are several ways to initialize a C++ pair:

  1. Using make_pair function:
 
#include <utility>
#include <iostream>
int main()
{
auto p = std::make_pair(1, "hello");
std::cout << p.first << " " << p.second << std::endl;
return 0;
}
Copy code

Output:

1 hello

2. Using the pair constructor:

 
#include <utility>
#include <iostream>
int main()
{
std::pair<int, std::string> p(1, "hello");
std::cout << p.first << " " << p.second << std::endl;
return 0;
}
Copy code

Output:

1 hello

3. Using uniform initialization:

 
#include <utility>
#include <iostream>
int main()
{
std::pair<int, std::string> p{1, "hello"};
std::cout << p.first << " " << p.second << std::endl;
return 0;
}
Copy code

Output:

1 hello

4. Using direct assignment:

 
#include <utility>
#include <iostream>
int main()
{
std::pair<int, std::string> p;
p.first = 1;
p.second = "hello";
std::cout << p.first << " " << p.second << std::endl;
return 0;
}
Copy code

Output:

1 hello

In each of these examples, a pair object is created with first set to 1 and second set to “hello”. The output of each program will be 1 hello.

Common C++ Pairs STL Functions

Here is a table of some commonly used C++ pair Standard Template Library (STL) functions:

Function Description
make_pair Constructs a pair object with the given values.
pair.first Accesses the first element of the pair.
pair.second Accesses the second element of the pair.
swap(pair1, pair2) Swaps the elements of two pair objects.
operator==(pair1, pair2) Compares two pair objects for equality.
operator!=(pair1, pair2) Compares two pair objects for inequality.
operator<(pair1, pair2) Determines if the first pair object is less than the second pair object.
operator>(pair1, pair2) Determines if the first pair object is greater than the second pair object.
operator<=(pair1, pair2) Determines if the first pair object is less than or equal to the second pair object.
operator>=(pair1, pair2) Determines if the first pair object is greater than or equal to the second pair object.

Please note that this is not an exhaustive list of all pair functions available in the C++ STL.

Must Read: Understanding for loop in C++

Must Read: Difference between While and Do while Loop in C++

Example of C++ Pairs

Example 1:

 
#include <iostream>
#include <utility>
#include <vector>
int main()
{
// Initializing a pair using make_pair
std::pair<int, std::string> p1 = std::make_pair(1, "one");
std::cout << "First element of pair p1: " << p1.first << std::endl;
std::cout << "Second element of pair p1: " << p1.second << std::endl;
// Initializing a pair using constructor
std::pair<int, std::string> p2(2, "two");
std::cout << "First element of pair p2: " << p2.first << std::endl;
std::cout << "Second element of pair p2: " << p2.second << std::endl;
// Initializing a vector of pairs
std::vector<std::pair<int, std::string>> v;
v.push_back(std::make_pair(3, "three"));
v.push_back(std::make_pair(4, "four"));
v.push_back(std::make_pair(5, "five"));
// Printing the vector of pairs
for (const auto &p : v)
{
std::cout << "First element of pair: " << p.first << std::endl;
std::cout << "Second element of pair: " << p.second << std::endl;
}
return 0;
}
Copy code

Output 1

First element of pair p1: 1
Second element of pair p1: one
First element of pair p2: 2
Second element of pair p2: two
First element of pair: 3
Second element of pair: three
First element of pair: 4
Second element of pair: four
First element of pair: 5
Second element of pair: five

This program creates three pair objects and adds them to a vector. The program then iterates through the vector and prints the first and second elements of each pair.

Must Read: Recursion in C++

Must Read: if-else in C++

Example 2:

 
#include <iostream>
#include <utility>
#include <map>
#include <string>
int main()
{
// Defining a map of employees and their respective ages
std::map<std::string, int> employees = {
{"John", 25},
{"Jane", 30},
{"Bob", 35}
};
// Iterating through the map and printing employee names and their ages
for (const auto &employee : employees)
{
std::cout << "Employee name: " << employee.first << std::endl;
std::cout << "Employee age: " << employee.second << std::endl;
}
// Adding a new employee to the map
employees.insert(std::make_pair("Samantha", 28));
// Finding the age of an employee using find function
auto it = employees.find("Jane");
if (it != employees.end())
{
std::cout << "Jane's age is: " << it->second << std::endl;
}
else
{
std::cout << "Jane not found." << std::endl;
}
return 0;
}
Copy code

Output 2:

Employee name: Bob
Employee age: 35
Employee name: Jane
Employee age: 30
Employee name: John
Employee age: 25
Jane's age is: 30

In this example, a map of employees and their respective ages is defined. The program then iterates through the map and prints the name and age of each employee. A new employee is added to the map using the insert function. Finally, the program uses the find function to search for the age of an employee, and if found, prints the age.

Nested C++ Pairs

Nested C++ pairs are pairs that contain other pairs as their elements. In other words, a pair can have its first or second element as another pair, allowing you to create more complex data structures. For example, you can create a pair that contains two pairs, and each of those pairs contains two integers. This allows you to represent a two-dimensional structure as a single entity. Nested pairs can be used to create complex data structures or to return multiple values from a function, which can be useful in certain situations.

Here’s an example of nested pairs in C++:

 
#include <iostream>
#include <utility>
int main()
{
std::pair<std::pair<int, int>, std::pair<int, int>> nested_pair;
nested_pair.first.first = 10;
nested_pair.first.second = 20;
nested_pair.second.first = 30;
nested_pair.second.second = 40;
std::cout << "First pair: " << nested_pair.first.first << " " << nested_pair.first.second << std::endl;
std::cout << "Second pair: " << nested_pair.second.first << " " << nested_pair.second.second << std::endl;
return 0;
}
Copy code

Output:

First pair: 10 20
Second pair: 30 40

In this example, a nested pair is created and initialized with four integers. The program then accesses and prints the values of the nested pairs.

Endnotes

Hope this article helped you grasp the concept of pairs in C++. The C++ pair container is a simple yet powerful data structure that allows you to store two disparate elements as a single entity.

Explore our C++ articles to find out more about the language and consolidate your knowledge of the fundamentals.

Contributed By: Prerna Singh

About the Author

This is a collection of insightful articles from domain experts in the fields of Cloud Computing, DevOps, AWS, Data Science, Machine Learning, AI, and Natural Language Processing. The range of topics caters to upski... Read Full Bio