我試圖通過閱讀這篇文章來了解弱排序的作業原理:https ://medium.com/@shiansu/strict-weak-ordering-and-the-c-stl-f7dcfa4d4e07
主要的收獲是:
那么對于嚴格的弱排序,我們必須有 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
下面的代碼將如何作業?例如,如果有人比較 x1 和 x2,我的比較函式將為 func(x1,x2) 和 func(x2,x1) 回傳 false。然后弱排序被打破,因為我認為第 2 條規則被打破了。我的理解不正確嗎?
#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;
}
uj5u.com熱心網友回復:
代碼很好。
當值x1和x2比較時,規則 2 得到滿足:規則說“如果 x < y,那么其他東西”。由于 IF 部分為假(x1不小于x2),因此整個陳述為真。
這就是含義(“IF ... THEN ...”)的作業原理。它是數理邏輯的一條基本規則:當前提條件不滿足時,整個陳述為真。
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/463568.html
上一篇:按物件的變數對物件的向量進行排序
