Different types for `std::sort` comparator in C++

  • A+
Category:Languages

When we provide a comparator function for std::sort, we use following overload of std::sort:

template< class RandomIt, class Compare > void sort( RandomIt first, RandomIt last, Compare comp ); 

in which comparator function for std::sort should have the following syntax:

bool cmp(const Type1 &a, const Type2 &b); 

But as you see a and b may have different types. cppreference says:

The types Type1 and Type2 must be such that an object of type RandomIt can be dereferenced and then implicitly converted to both of them. ​

But I still cannot get it exactly how we can have 2 different types in a single array when we try to sort it.

Is ti possible that someone provide a small example with different types for std::sort's comparator function?

UPDATE:

even though my question is answered, I found this situation interesting in multiple inheritance. Here a small code for it, but in reality I don't know if I ever need this:

#include<iostream>  #include<vector> #include<algorithm> using namespace std;   class A  {  public:    int x; };   class B  {  public:    int y; };   class C: public B, public A  // Note the order  { public:     C(int v1, int v2) {this->x = v1; this->y = v2; } };   bool cmp(const A& v1, const B& v2) {     return v1.x < v2.y; }  int main()  {      vector<C> data;     data.push_back(C(2,3));     data.push_back(C(1,2));     data.push_back(C(2,1));     data.push_back(C(2,5));     sort(data.begin(), data.end(), cmp);      for (auto val : data) {         cout << val.x << " " << val.y << endl;     } }  

 


Its not about what is stored in the array. It is about what the comparator function is. Take for example this:

struct Animal {}; struct Cat : Animal {}; struct Dog : Animal {}; struct Hound : Dog {};  bool cmp(const Animal &a, const Animal &b); 

Even if you have a list of Dogs, Cats or Hounds you can still sort them with the function cmp because they are all implicitly convertible. ie.

std::vector<Hound> hounds; ... // fill hounds std::sort(hounds.begin(), hounds.end(), cmp); 

And you can even imagine cases where Type1 and Type2 are not the same, eg.:

bool cmp(const Animal &a, const Dog &b); // Special compare to make dogs at the                                          // front because dogs are better! etc ... 

The types Type1 (Animal) and Type2 (Dog) must be such that an object of type RandomIt (Hound) can be dereferenced and then implicitly converted to both of them. ​Which is true.

Comment

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: