C++ :STD ::如何根据弱排序原理排序平等要素的向量
我试图通过阅读本文来理解弱点的工作原理: https://medium.com/@shiansu/strict-weak-ordering-and-and-the-c-stl-f7dcfa4d4e07
主要的收获是:
那么,对于严格的弱点,我们必须拥有 对于所有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;
}
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;
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
代码很好。
当值
x1
和x2
的值时,满足规则2:规则说“如果x&lt; y,则是其他东西”。由于if零件为false(x1
不小于x2
),因此整个语句都是正确的。这就是含义(“如果...然后……”)的含义。这是数学逻辑的基本规则:当不满足前提条件时,整个语句是正确的。
The code is good.
When the values
x1
andx2
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 thanx2
), 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.