Pair in STL - C++


Hello coders , We welcome you all to learn a new concept on std::pair. Generally, a pair is combination of two objects which had a well defined meaning .So let's jump in,

Definition:

The pair in the C++ standard template library is defined under utility library and it is used to store two data elements or objects of same or different datatype.
● To access first element of pair ,we can use the pair_name followed by dot operator followed by a member variable "first" (member variable is declared inside the pair class ) and second element of the pair can be access using the pair_name followed by dot operator followed by a member variable "second".

● Pair is heterogeneous i.e. it allows to store a variable of different data types.

● Pair can be assigned ,compared and copied.


Logical operators(=,==,!=.>=,<=) :

We can use these operators with the pairs

1. assignment operator(=): This operator assign the right pair object of into the left pair object .
pair& operator= (const pair& pr);

Member first of left pair object is assigned pr.first , and member second of left pair object is assigned pr.second.

2. equal operator(==): This operator compares the member variable of two pair objects.

Two pair objects compare equals and result a boolean true if pair1.first is equal to pair2.first and pair1.second is equal to pair2.second or else it returns false .

3. Not equal operator(!=): This operator return true if both of the member variable(i.e. p1.first != p2.first && p1.second!=p2.second) are not equal or return false.

Similarly, operators <, >, <= and >= perform a lexicographical comparison on the sequence formed by members first and second in all cases using operator<reflexively for the comparisons).

Let's see an example program on logical operator

Output:

First element = 10 second element = 100
--------------------------------------------------------------------
First element = 10 second element = 100
--------------------------------------------------------------------
First element = 10 second element = 10
--------------------------------------------------------------------
Both pairs are equal
Both pairs are not equal
1
1
0
1

4. Swap(): This function swaps the contents of one pair object with the contents of another pair object. The pairs must be of same type.

Output:

First element = 20 second element = 200
--------------------------------------------------------------------
First element = 10 second element = 100
--------------------------------------------------------------------


So that’s it for this article we will be coming up with our next article very soon till then keep learning, keep coding, keep reading and keep improving !!

Happy Coding 😊
By Programmers Army