Open In App

How to Compare Two Pairs in C++?

In C++, a pair is used to combine together two values that may be of different data types. Pair provides a way to store two heterogeneous objects as a single unit. In this article, we are going to explore how we can compare two pairs in C++.

Example



Input:
pair1={1,”GfG”};
pair2= {1,”GfG”}
Output: Pairs are equal

Compare pairs in C++

We can simply use the Equal to(==)comparison operator to check if two pairs are equal or not. For The two given pairs say pair1 and pair2, the Equal to(==) operator compares the “first value and second value of those two pairs i.e. if pair1.first is equal to pair2.first or not” and “if pair1.second is equal to pair2.second or not”.

In the following example we will compare two pairs storing an integer and a string.






#include<bits/stdc++.h>
using namespace std;
  
  
int main() {
      
    pair<int, string> pair1 = {1, "GfG"};
    pair<int, string> pair2 = {1, "GfG"};
      pair<int, string> pair3 = {2, "GfG"};
      
    // check if two given pairs are equal or not
      
    if (pair1 == pair2) {
        cout << "Pairs are equal." << endl;
    } else {
        cout << "Pairs are not equal." << endl;
    }
    
       if (pair1 == pair3) {
        cout << "Pairs are equal." << endl;
    } else {
        cout << "Pairs are not equal." << endl;
    }
  
    return 0;
}

Output
Pairs are equal.
Pairs are not equal.


Time Complexity: O(1)

Auxilary Space: O(1)

Note: Two pairs can only be compared if they are of the same data type, and two pairs are equal when both the first and second values of each pair matches with each other.

Article Tags :