c++comparecomparisonstd-pair

Comparing pairs separately for equality, less and greater.


Lets say that I have a pair of std::pair<int, int>s. I want each time I compare them to emit a separate code for equality, less and greater (e.g., 0, -1 and 1 respectively).

The naive approach would be to write some if-else code:

int compare_int_pairs(std::pair<int, int> const &p1_, std::pair<int, int> const &p2_) {
  if(p1_.first < p2_.first) {
    return -1;
  } else if(p1_.first > p2_.first) {
    return 1;
  } else {
     if(p1_.second < p2_.second) {
       return -1;
     } else if(p1_.second > p2_.second) {
       return 1;
     } else {
       return 0;
     }
  }

  return 0;
}

But is there a better and more efficient way to do this (e.g., bitwise operations or something else)?


Solution

  • If you don't insist on the values -1, 0 and 1 but are also ok with negative, 0 and positive as result, this is the fastest I could come up with:

    #include <utility>
    #include <stdint.h>
    
    int compare_int_pairs(std::pair<int, int> const &p1_, std::pair<int, int> const &p2_) {
        int ret = p1_.first - p2_.first;
        if (ret == 0) ret = p1_.second - p2_.second;
        return  ret;
    }
    

    Assembly