Think you can solve it :)? We all know it is expected that contradictory comparison functions may cause Runtime Error when used by the sort method. For instance, one could try sorting an array using a function that only returns True!
However, when seemingly equivalent procedures start giving different results, curiosity strikes!
Take this example:
"numbers[i].z = 2;" line with something like "numbers[i].z = i%10;". But we will focus on this case, on which it does not result in error.
By now you must've noticed this struct basically simulates the sorting of an integer array, except for the <= comparison. So, one would expect an int array to behave similarly, when using a similar comparison function! Yet...
However, when seemingly equivalent procedures start giving different results, curiosity strikes!
Take this example:
struct number{Note the operator< returns <=. In some cases this would cause a Runtime Error, such as if you replaced the
int z;
const bool operator< (const number &that) const{
return z <= that.z;
}
}numbers[10000];
int main (){
for(int i = 0; i < 10000; i++){
numbers[i].z = 2;
}
sort(numbers, numbers+10000);
return 0;
}
"numbers[i].z = 2;" line with something like "numbers[i].z = i%10;". But we will focus on this case, on which it does not result in error.
By now you must've noticed this struct basically simulates the sorting of an integer array, except for the <= comparison. So, one would expect an int array to behave similarly, when using a similar comparison function! Yet...
int array[10000];If you try to execute this piece of code, although it inherently seems to be doing exactly the same as the one above, a Runtime Error will occur this time. Can you guess why? :)
const bool myfunc (int a, int b){
return a <= b;
}
int main (){
for(int i = 0; i < 10000; i++){
array[i] = 2;
}
sort(array, array+10000, myfunc);
return 0;
}
If your operator< is incorrect, sort, lower_bound and other STL structures can crash.