For working professionals
For fresh graduates
More
Explore C++ Tutorials: Explori…
1. The Ultimate C++ Guide: C++ Tutorial for Beginners
2. Application of C++
3. C++ Hello World Program
4. C++ Variable
5. Reference Variable in C++
6. Function Overloading in C++
7. Functions in C++
8. Pointer in C++
9. Data Types in C++
10. C++ for Loop
11. While Loop in C++
12. C++ Lambda
13. Loop in C++
14. Switch Case in C++
15. Array in C++
16. Strings in C++
17. Substring in C++
18. Class and Object in C++
19. Constructor in C++
20. Copy Constructor in C++
21. Destructor in C++
22. Multiple Inheritance in C++
23. Encapsulation in C++
24. Single Inheritance in C++
25. Friend Class in C++
26. Hierarchical Inheritance in C++
27. Virtual Base Class in C++
28. Abstract Class in C++
29. Vector in C++
30. Map in C++
31. Pair in C++
Now Reading
32. Initialize Vector in C++
33. Iterators in C++
34. Queue in C++
35. Priority Queue in C++
36. Stack in C++
37. ifstream in C++
38. Exception Handling in C++
39. Memory Management in C++
40. Templates in C++
41. Type Conversion in C++
42. Enumeration in C++
43. Namespace in C++
44. Set Precision in C++
45. Stringstream in C++
46. Recursion in C++
47. Random Number Generator in C++
48. C++ Shell
49. Setw in C++
50. Multithreading in C++
51. Atoi in C++
52. Call by Value and Call by Reference in C++
53. Difference Between C and C++
54. C# vs C++
55. C++ GUI
56. C++ Game Code
57. Class in C++
58. C++ Header Files
59. Power Function in C++
60. Data Hiding in C++
61. Inline Function in C++
62. Getline Function in C++
63. Cin in C++
64. Printf in C++
65. Struct in C++
66. C++ List
67. static_cast in C++
68. C++ Comments
69. Structures in C++
70. C++ Standard Template Library (STL)
71. Virtual Function in C++
72. Sorting in C++
73. Polymorphism in C++
74. Oops Concepts in C++
75. Converting Integers to Strings in C++
76. Differences Between Break and Continue
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!
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.
So, why use pairs in C++? There are several compelling reasons to incorporate pairs into your coding toolkit:
Let’s consider a practical scenario where pair in C++ shines:
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.
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 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.
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.
C++ provides a set of comparison operators that can be used with pairs, including:
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.
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.
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!
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.
Author
Start Learning For Free
Explore Our Free Software Tutorials and Elevate your Career.
Talk to our experts. We are available 7 days a week, 9 AM to 12 AM (midnight)
Indian Nationals
1800 210 2020
Foreign Nationals
+918045604032
1.The above statistics depend on various factors and individual results may vary. Past performance is no guarantee of future results.
2.The student assumes full responsibility for all expenses associated with visas, travel, & related costs. upGrad does not provide any a.