C++ Compare operators


Parameters of these operators are lhs and rhs

  • operator== tests if both elements on lhs and rhs pair are equal. The return value is true if both lhs.first == rhs.first AND lhs.second == rhs.second, otherwise false
std::pair<int, int> p1 = std::make_pair(1, 2);
std::pair<int, int> p2 = std::make_pair(2, 2);

if (p1 == p2)
    std::cout << "equals";
    std::cout << "not equal"//statement will show this, because they are not identical
  • operator!= tests if any elements on lhs and rhs pair are not equal. The return value is true if either lhs.first != rhs.first OR lhs.second != rhs.second, otherwise return false.

  • operator< tests if lhs.first<rhs.first, returns true. Otherwise, if rhs.first<lhs.first returns false. Otherwise, if lhs.second<rhs.second returns true, otherwise, returns false.

  • operator<= returns !(rhs<lhs)

  • operator> returns rhs<lhs

  • operator>= returns !(lhs<rhs)

    Another example with containers of pairs. It uses operator< because it needs to sort container.

#include <iostream>
#include <utility>
#include <vector>
#include <algorithm>
#include <string>
int main()
    std::vector<std::pair<int, std::string>> v = { {2, "baz"},
                                                   {2, "bar"},
                                                   {1, "foo"} };
    std::sort(v.begin(), v.end());
    for(const auto& p: v) {
        std::cout << "(" << p.first << "," << p.second << ") ";
        //output: (1,foo) (2,bar) (2,baz)