1

std::pair's default comparison operators uses the first element of the pair, but I would like to compare by the second element.

I could easily define something like this:

bool operator>(std::pair<int, int> p1, std::pair<int, int> p2)
{
   return p1.second > p2.second;
}

so that the second element is used.

However I was playing around and if I call std::greater<std::pair<int,int>>()(p1,p2) it still compares the pairs according to the first element instead of using the operator> I defined. Why is this the case?

Here's a complete example

#include <iostream>
#include <vector>

template<typename T>
bool operator>(std::pair<T, double> p1, std::pair<T, double> p2)
{
   return p1.second > p2.second;
}

int main( ) 
{ 
   std::pair<int, double> p1(2, 4.03);
   std::pair<int, double> p2(3, 4.02);

   std::cout << (p1 > p2) << std::endl;
   std::cout << (std::greater<>()(p1,p2)) << std::endl;

   return 0;
}

The program prints

1
0

So it appears that the functor is not using the operator> that I defined.

24n8
  • 1,898
  • 1
  • 12
  • 25

0 Answers0