Home > Mobile >  c : How does std::sort a vector of equal elements based on weak ordering principle
c : How does std::sort a vector of equal elements based on weak ordering principle

Time:04-25

I am trying to understand how weak ordering works by reading this article : https://medium.com/@shiansu/strict-weak-ordering-and-the-c-stl-f7dcfa4d4e07

The main take away from it is :

Then for strict weak ordering we must have For all x:

x < x is never true, everything should be equal to itself
If x < y then y < x cannot be true
If x < y and y < z then x < z, the ordering should be transitive
If x == y and y == z then x == z, equality should be transitive

How would the below code work ? For example , if someone compares x1 and x2 my compare function will return false for both func(x1,x2) and func(x2,x1). Then weak ordering is broken because rule number 2 is broken I think . Is my understanding incorrect ?

#include <iostream>
#include <vector>
#include <algorithm>

using namespace std;

struct x
{
    int a ;
    x()
    {
        a = 3;
    }
};
bool func(const x& x1,const x& x2)
{
    if (x1.a < x2.a )
      return true;
      
    return false;
}
int main()
{
   cout << "Hello World" << endl; 
   std::vector<x> vec;
   x x1 , x2, x3 , x4 , x5, x6, x7;
   x1.a = 5;
   x2.a = 5;
   x3.a = 5;
   x7.a = 5;
   vec.push_back(x1);
   vec.push_back(x2);
   vec.push_back(x3);
   vec.push_back(x4);
   vec.push_back(x5);
   vec.push_back(x6);
   vec.push_back(x7);
   
   std::sort (vec.begin(), vec.end(), func);
   
   return 0;
}

CodePudding user response:

The code is good.

When the values x1 and x2 are compared, rule 2 is satisfied: The rule says "IF x < y, THEN something else". Since the IF part is false (x1 is not less than x2), the entire statement is true.

That is how implications ("IF ... THEN ...") work. It is a basic rule of mathematical logic: when the precondition is not satisfied, the entire statement is true.

  • Related