Mox
Mox

Reputation: 2463

std::sort on pair which the 2nd element has no comparator

I am trying to figure out how is it that the following code is being compiled without warning/error.

This is the the piece of code that I see in the project that I am working on in office. (variable/class name has been changed)

vector<pair<time_t, ClassA *> > vec = getVecFromSomewhere();
std::sort(vec.begin(), vec.end());    

I have checked the source code of ClassA, which I do not see any comparator being implemented. So is it true that only the first element of a pair requires comparator?

Edit: all instances of ClassA originate from the same vector.

Upvotes: 2

Views: 146

Answers (2)

krzaq
krzaq

Reputation: 16421

Your understanding is incorrect. std::pair defines operator<. It compares lexicographically, that is, the second elements are only compared if the first are equal.

The exact standardese (n4606):

template <class T1, class T2>

constexpr bool operator<(const pair<T1, T2>& x, const pair<T1, T2>& y)

Returns: x.first < y.first || (!(y.first < x.first) && x.second < y.second).

This case is a bit special, because it's undefined to compare pointers to objects that are not parts of the same object/array.

Upvotes: 3

TartanLlama
TartanLlama

Reputation: 65620

ClassA might not have an operator<, but that doesn't matter, because you're storing ClassA* in your pair, not ClassA. You can compare pointers, so your code works.

ClassA as [10];
as[0] < as[1]; //invalid, compares ClassAs
as < as+1; //valid, compares ClassA*s

Note that you need to be very careful with the semantics of your comparison. Do you really want to be comparing those pointers? Do they point to the same array object? If not, you're off into the fun fun land of undefined behaviour as soon as you compare them. If so, that ordering might still not be the one you want.

Upvotes: 5

Related Questions