Because comp1(a,b)
and comp1(b,a)
can both return true
, which isn’t allowed. std::sort
states that:
comp – comparison function object (i.e. an object that satisfies the requirements of Compare) which returns true if the first argument is less than (i.e. is ordered before) the second.
And following the link to Compare we also see:
Establishes strict weak ordering relation with the following properties
* For all a, comp(a,a)==false
* If comp(a,b)==true then comp(b,a)==false
* if comp(a,b)==true and comp(b,c)==true then comp(a,c)==true
Your first function, comp
, satisfies those requirements: no two objects could return true
. If comp(a,b)
returns true,
then comp(b,a)
returns false
; however, this is not the case in your second function, comp1
. comp1(a,b)
can return true
, as can comp(b,a)
, so sort
will never finish and therefore it won’t compile.
You state that
i want to put those same size strings together
But just using operator<
will achieve those results: any string the same size will be grouped together.
1
solved Why can not use “return lhs.size() == rhs.size()” in std::sort() compare function?