Блог пользователя rtanmay

Автор rtanmay, история, 8 лет назад, По-английски

Hello,

I was solving this problem. In this I have sorted the array of structures.

//This is my structure:
typedef struct node
{
	int a,b,c;
} node;

Submission

//This gets runtime error on test-32.
//Error: comparison doesn't meet irreflexive requirements, assert(!(a < a)).
bool compare(node n1, node n2)
{
	if(n1.c > n2.c) return false;
	else return true;
}

Submission

//However this gets accepted, only change is in >=
bool compare(node n1, node n2)
{
	if(n1.c >= n2.c) return false;
	else return true;
}

Why is this error coming? I thought even if we give only > then for equal value it will return true, so there should not be any problem between comparison of equal elements.

Thank you

  • Проголосовать: нравится
  • -5
  • Проголосовать: не нравится

»
8 лет назад, скрыть # |
← Rev. 2  
Проголосовать: нравится 0 Проголосовать: не нравится

because if x = y then both x < y and y < x according to your first submission. It causes UB while sorting.

»
8 лет назад, скрыть # |
 
Проголосовать: нравится +6 Проголосовать: не нравится

The comparator function in stl::sort() follows and requires strict weak ordering.

eg. Consider Comp for ascending order:

bool comp(int x, int y){   
    if(x < y) return true;  // this will ensure that x comes before y if and only if(x < y).
    return false;
}

And This is what you are doing :

bool comp(int x, int y){   
    if(x > y) return false;  // this function will return true even when (x == y) which does not follow
    return true;             // strict weak ordering.
}

Your accepted solution solves this problem and that is why it is not throwing any error.