1. Home
C++ Tutorial

Explore C++ Tutorials: Exploring the World of C++ Programming

Discover comprehensive C++ tutorials designed for beginners and advanced programmers alike. Enhance your coding skills with step-by-step guides and practical examples.

  • 77 Lessons
  • 15 Hours
right-top-arrow
30

Pair in C++: A Complete Guide

Updated on 27/09/2024419 Views

Allow me to introduce one of the most exciting things I've discovered in C++: pair in C++. If you have ever needed to handle two related values and thought that there must be a better way than using two different variables, then this is your answer. A pair in C++ refers to a container that can store precisely two values. It's time for me to talk about one of the most important parts in C++. This part is called 'pair'. If you ever had two numbers or words that were connected and felt like it would be nicer if they could fit into a single container, well guess what? It's possible with pairs! A 'pair' specifically means a container where we can put exactly TWO values together. These values can be of different types, making pairs incredibly flexible and useful.

At the beginning of my journey with C++, I frequently had to handle pairs of related data. For instance, dealing with coordinates (x, y) where every point has two values. I could use two individual variables for this task but it was not very organized. At this point, I encountered the cpp pair. It is a special element available in the <utility> header. As its name implies, pair allows you to unite these two values together. This presents an organized and easy way of handling them.

In this tutorial, I’ll guide you through the pair world in C++ and we’ll cruise over all the important ideas about CPP pair. This includes what is pair in CPP, how to make pair in C++, pair in C++ vector and many others.

So, let’s begin!

What is a Pair in C++?

First, let's begin with the essentials: What does a pair in C++ mean? Essentially, a pair is a basic container from the Standard Template Library (STL) of C++. It can store two elements precisely, known as first and second. The great convenience of pairs is that they can have different data types for the two elements. This versatility makes pairs very useful in many programming jobs.

To use pairs in C++, you need to include the <utility> header file:

#include <utility>

Now, let’s see an example of how to define and use a pair in C++:

Code: 

#include <iostream>

#include <utility>

int main() {

    std::pair<int, std::string> myPair(1, "Hello, Pair!");

    std::cout << "First: " << myPair.first << ", Second: " << myPair.second << std::endl;

    return 0;

}

Output: 

First: 1, Second: Hello, Pair!

In this C++ pair example, we created a pair that holds an int and a std::string. The first element is an integer, and the second element is a string. You can access these elements using the .first and .second members.

Why Use Pairs?

So, why use pairs in C++? There are several compelling reasons to incorporate pairs into your coding toolkit:

  1. Convenience and clarity: Pair in C++ provides a convenient way to group two related values together. For instance, when dealing with coordinates, you can use a pair to hold the x and y values. This makes your code more readable and organized.
  2. Data integrity: Using pairs helps maintain the integrity of related data. Instead of managing two separate variables, you bundle them together, reducing the risk of mismatched or incorrect data.
  3. Efficiency: CPP pair can simplify your code, making it more efficient. When you need to pass two related values to a function or return them from a function, using a pair is straightforward and reduces the need for creating custom structures or classes.
  4. STL compatibility: Pair in C++ are fully integrated with the C++ Standard Library, making them compatible with other STL containers and algorithms. For example, you can use pairs in a vector, which is especially useful for managing collections of related data.

Let’s consider a practical scenario where pair in C++ shines:

Storing Pair in C++ vector

Imagine you have a list of students and their scores. Using a vector of pairs, you can easily manage this data. Here’s how pair in C++ vector work: 

Code: 

#include <iostream>

#include <vector>

#include <utility>

int main() {

    std::vector<std::pair<int, std::string>> students;

    students.push_back(std::make_pair(1, "Alice"));

    students.push_back(std::make_pair(2, "Bob"));

    for (const auto& student : students) {

        std::cout << "ID: " << student.first << ", Name: " << student.second << std::endl;

    }

    return 0;

}

Output: 

ID: 1, Name: Alice

ID:2, Name: Bob

In this given example, we utilize a pair in C++ vector to keep student IDs and names. The usage of pairs combined with vectors offers an effective method for managing groups of data.

Creating Pairs with make_pair

The make_pair function is another reason why pairs are so convenient. It simplifies the creation of pairs without having to specify the types explicitly. Here’s how you use make_pair:

Code: 

#include <iostream>

#include <utility>

int main() {

    auto myPair = std::make_pair(1, "Hello, make_pair!");

    std::cout << "First: " << myPair.first << ", Second: " << myPair.second << std::endl;

    return 0;

}

Output: 

First: 1, Second: Hello, make_pair!

Comparing Pairs

Comparing pair in C++ is both intuitive and powerful. One of the key strengths of pairs in C++ is their ability to be compared using the standard comparison operators. This feature makes pairs especially useful in scenarios where ordering and sorting are essential.

Lexicographical Comparison

Pairs are compared lexicographically. This means that the comparison first checks the first elements of each pair. If the first elements are different, the result of the comparison is determined by these elements. If the first elements are equal, the comparison then proceeds to the second elements. This two-step process ensures that pairs can be compared in a natural and logical manner.

Here's a simple example to illustrate how lexicographical comparison works:

Code: 

#include <iostream>

#include <utility>

int main() {

    std::pair<int, int> pair1(1, 2);

    std::pair<int, int> pair2(1, 3);

    if (pair1 < pair2) {

        std::cout << "pair1 is less than pair2" << std::endl;

    } else {

        std::cout << "pair1 is not less than pair2" << std::endl;

    }

    return 0;

}

Output: 

pair1 is less than pair2

In this instance, we possess a vector which holds pairs. Each pair contains an integer and a string. The function std::sort arranges these pairs in ascending order, sorting is based on the first element of each pair. If initial elements are equivalent then comparison happens using second elements for such pairs.

Comparison Operators

C++ provides a set of comparison operators that can be used with pairs, including:

  • == (equal to)
  • != (not equal to)
  • < (less than)
  • <= (less than or equal to)
  • > (greater than)
  • >= (greater than or equal to)

These operators make it easy to compare pairs directly. Here’s how you can use these operators:

Code: 

#include <iostream>

#include <utility>

int main() {

    std::pair<int, std::string> pair1(1, "Apple");

    std::pair<int, std::string> pair2(2, "Banana");

    if (pair1 == pair2) {

        std::cout << "pair1 is equal to pair2" << std::endl;

    } else if (pair1 != pair2) {

        std::cout << "pair1 is not equal to pair2" << std::endl;

    }

    if (pair1 < pair2) {

        std::cout << "pair1 is less than pair2" << std::endl;

    } else if (pair1 > pair2) {

        std::cout << "pair1 is greater than pair2" << std::endl;

    }

    return 0;

}

Output: 

pair1 is not equal to pair2

pair1 is less than pair2

In this code snippet, we compare two pairs using different comparison operators. The == and != operators check for equality and inequality, respectively. The < and > operators compare pairs lexicographically.

Practical Use Case: Sorting Pairs

One of the most practical applications of comparing pairs is in sorting. Since pairs can be compared using the standard comparison operators, they can be sorted naturally using the std::sort function from the <algorithm> header.

Consider the following example, where we sort a vector of pairs:

Code: 

#include <iostream>

#include <vector>

#include <algorithm>

#include <utility>

int main() {

    std::vector<std::pair<int, std::string>> vec;

    vec.push_back(std::make_pair(3, "Charlie"));

    vec.push_back(std::make_pair(1, "Alice"));

    vec.push_back(std::make_pair(2, "Bob"));

    std::sort(vec.begin(), vec.end());

    for (const auto& p : vec) {

        std::cout << "First: " << p.first << ", Second: " << p.second << std::endl;

    }

    return 0;

}

In this example, pair1 is smaller than pair2 because the second element of pair1 (which is 2) is smaller than the second element of pair2 (which is 3). As for the first elements of both pairs, they are equal to 1. Therefore, we proceed with comparing their second elements.

This capability to compare and sort pairs efficiently is invaluable when dealing with collections of related data, such as sorting records by multiple criteria or managing priority queues.

Concluding Remarks

Understanding how to compare pairs in C++ adds a powerful tool to your programming toolkit. Lexicographical comparison ensures that pairs can be compared in a logical and consistent manner. The ability to use standard comparison operators with pairs simplifies many common tasks, such as sorting and managing collections of data.

I hope this deeper dive into cpp pair, including make pair in C++ and C++ pair examples has clarified their utility and versatility. If you’re keen on mastering more advanced C++ concepts and software engineering practices, consider exploring upGrad’s Software Engineering Course. Happy coding!

FAQs About Pairs in C++

1. What is a pair in C++?

A pair in C++ is a container that holds two values of possibly different types.

2. How do I create a pair in C++?

You can create a pair using the std::pair constructor or the make_pair function.

3. Can I have a pair of different types in C++?

Yes, a pair can hold two values of different types.

4. How do I compare pairs in C++?

Pairs are compared lexicographically, first comparing the first elements and then the second if the first are equal.

5. Are pairs mutable in C++?

Yes, the elements of a pair can be modified.

6. Are there any alternatives to pairs in C++?

Yes, you can use structures or classes if you need more than two values or more complex operations.

7. Can I use pairs in set C++?

Yes, pairs can be used as elements in sets, provided they are comparable.

8. Can a pair be null in C++?

No, a pair must always contain two values.

Abhimita Debnath

Abhimita Debnath

Abhimita Debnath is one of the students in UpGrad Big Data Engineering program with BITS Pilani. She's a Senior Software Engineer in Infosys. She…Read More

Need Guidance? We're Here to Help!
form image
+91
*
By clicking, I accept theT&Cand
Privacy Policy
image
Join 10M+ Learners & Transform Your Career
Learn on a personalised AI-powered platform that offers best-in-class content, live sessions & mentorship from leading industry experts.
right-top-arrowleft-top-arrow

upGrad Learner Support

Talk to our experts. We’re available 24/7.

text

Indian Nationals

1800 210 2020

text

Foreign Nationals

+918045604032

Disclaimer

upGrad does not grant credit; credits are granted, accepted or transferred at the sole discretion of the relevant educational institution offering the diploma or degree. We advise you to enquire further regarding the suitability of this program for your academic, professional requirements and job prospects before enr...