🍐

Pairs

 
In C++, pair is a template class that represents a pair of values of different data types. It is used when we need to associate two values and treat them as a single unit. pair is useful in a number of applications such as storing and manipulating key-value pairs, data structures like graphs and trees where each node has a pair of values, or in sorting and searching algorithms where each element is a pair of values.
 
#include <iostream> #include <utility> using namespace std; int main() { // Create a pair of integers pair<int, int> myPair(1, 2); // Access the first and second elements of the pair cout << "First element: " << myPair.first << endl; cout << "Second element: " << myPair.second << endl; // Modify the first and second elements of the pair myPair.first = 10; myPair.second = 20; // Print the modified pair elements cout << "Modified pair elements: (" << myPair.first << ", " << myPair.second << ")" << endl; return 0; }
 
In this implementation, we create a pair of integers myPair with values 1 and 2 using the pair<int, int> template. We then access the first and second elements of the pair using the first and second attributes and print them to the console.
Using the first and second attributes of the pair, we then modify the values of the pair and again print them to the console.
This implementation demonstrates how we can use the pair template class to create a pair of values of two different data types, modify values in the pair and access values in the pair. In various use cases, pair can help us to simplify the code and improve code readability.