











Pair in STL C++
About Pair in STL :
Pair in STL is defined as the container used to store two heterogeneous units together. It is basically used to store tuples.


Syntax of Pair :
pair< data_type, data_type> pair_name;
Pair is a container that is given by the “utility” library and is declared in C++ by using the keyword “pair”. In essence, a pair is used to combine two components or values into one, allowing for the storage of things with various data types or two heterogeneous objects as a single entity. Only two components can be stored in the pair container, the first of which can only be referred by “first” and the second of which can only be stored in “second”.
Functions in Pair :
Function | Working |
---|---|
make_pair() | store two values in the pair. |
swap() | swap the components of pair 1 and pair 2. |
tie() | unpacks the pair values into independent variables |
Example of Pair in STL :
#include<iostream #include<bits/stdc++.h> using namespace std; int main() { pair<int, int> p1; pair<string, int> p2("PrepInsta",1); p1.first = 2; p1.second = 3; cout<<"The elements in pair p1 : "; cout<< p1.first<<" "<< p1.second<< endl; cout<<"The elements in pair p2: "; cout<< p2.first<<" "<< p2.second; return 0; }
Output :
The elements in pair p1 : 2 3 The elements in pair p2: PrepInsta 1
In the above program, take two pair p1 and p2, insert value in pair p1 and p2, print them on the screen.
Example of Pair in STL:
#include<iostream> #include<bits/stdc++.h> using namespace std; int main() { pairp1; pair p2(100,1); p1 = make_pair(2,3); // function to insert value in pair cout<<"The elements in pair p1 before swapping : "; cout<< p1.first<< " "<< p1.second<< endl; cout<<"The elements in pair p2: "; cout<< p2.first<< " "<< p2.second<< endl; p1.swap(p2); // swap function n pair cout<<"The elements in pair p1 after swapping : "; cout<< p1.first<< " " << p1.second; return 0; }
Output :
The elements in pair p1 before swapping : 2 3 The elements in pair p2: 100 1 The elements in pair p1 after swapping : 100 1
In the above program, take two pair p1 and p2, insert value in p2 by make_pair function while also use swap function swap the values of pair p2 and p1.
Prime Course Trailer
Related Banners
Get PrepInsta Prime & get Access to all 200+ courses offered by PrepInsta in One Subscription
Get over 200+ course One Subscription
Courses like AI/ML, Cloud Computing, Ethical Hacking, C, C++, Java, Python, DSA (All Languages), Competitive Coding (All Languages), TCS, Infosys, Wipro, Amazon, DBMS, SQL and others
Login/Signup to comment