# strict weak ordering导致公司级故障

## 背景

int priority;
int score;
};

• 按照priority升序排列

• 如果priority一样大，则按照score降序排列

if (item1.priority < item2.priority) {
return true;
} else if (item1.priority > item2.priority) {
return false;
}

return item1.score >= item2.score;
} );
}

## 原因

if (item1.priority < item2.priority) {
return true;
} else if (item1.priority > item2.priority) {
return false;
}

return item1.score >= item2.score;
} );
}

int main() {
/*
给v进行赋值操作
*/

return 0;
}

g++ -g test.cc -o test
./test

if (item1.priority < item2.priority) {
return true;
} else if (item1.priority > item2.priority) {
return false;
}

if (item1.score > item2.score) {
return true;
}

return false;
} );
}

Having a non-circular relationship is called non-transitivity for the < operator. It’s not too hard to realise that if your relationships are circular then you won’t be getting reasonable results. In fact there is a very strict set of rules that a data type and its comparators must abide by in order to get correct results from C++ STL algorithms, that is strict weak ordering.

## 严格弱序

A strict weak ordering is a binary relation < on a set S that is a strict partial order (a transitive relation that is irreflexive, or equivalently,[5] that is asymmetric) in which the relation "neither a < b nor b < a" is transitive.[1] Therefore, a strict weak ordering has the following properties:

• For all x in S, it is not the case that x < x (irreflexivity).
• For all x, y in S, if x < y then it is not the case that y < x (asymmetry).
• For all x, y, z in S, if x < y and y < z then x < z (transitivity).
• For all x, y, z in S, if x is incomparable with y (neither x < y nor y < x hold), and y is incomparable with z, then x is incomparable with z (transitivity of incomparability).

• x > y 等同于 y < x
• x == y 等同于 !(x < y) && !(x > y)

• 对于所有的x：x < x永远不能为true，每个变量值必须等于其本身
• 如果x < y，那么y < x就不能为true
• 如果x < y 并且y < z，那么x < z,也就是说有序性必须可传递性
• 如果x == y并且y == z，那么x == z，也就是说值相同也必须具有可传递性

sort
-> __introsort_loop
--> __unguarded_partition

template<typename _RandomAccessIterator, typename _Tp, typename _Compare>
_RandomAccessIterator
__unguarded_partition(_RandomAccessIterator __first,
_RandomAccessIterator __last,
_Tp __pivot, _Compare __comp)
{
while (true)
{
while (__comp(*__first, __pivot))
++__first;
--__last;
while (__comp(__pivot, *__last))
--__last;
if (!(__first < __last))
return __first;
std::iter_swap(__first, __last);
++__first;
}
}

while (__comp(*__first, __pivot))
++__first;

## 结语

posted @ 2022-01-06 15:49  高性能架构探索  阅读(249)  评论(3编辑  收藏  举报