简体   繁体   English

std :: sort可以使用不严格的弱排序比较器作为拓扑排序吗?

[英]could std::sort with not strict weak ordering comparator work as topological sorting?

I do know that I should follow strict weak ordering for c++ comparator. 我确实知道我应该遵循c ++比较器的严格弱排序。 And the main reason is that !(a > b) && !(b > a) should act as equivalence operator. 主要原因是!(a > b) && !(b > a)应该充当等价运算符。

But the problem is only sorting where you don't need equivalence operator not like std::set . 但是问题只是排序,不需要像std::set这样的等价运算符。

For example, there is vector of sets and if set A is proper subset of B, then after sorting, index of set A should be smaller than index of set B. 例如,存在集合的向量,并且如果集合A是B的适当子集,则在排序之后,集合A的索引应小于集合B的索引。

So assume that you write comparator like this 因此,假设您这样编写比较器

bool comparator(vector<int> &A, vector<int> &B) const {
    // if A is proper subset of B, return true
    // otherwise, return false
}

Then does std::sort with this comparator always work like topological sorting? 那么使用此比较器的std::sort总是像拓扑排序一样工作吗?

plus) 加)

thanks for Oliver Charlesworth for missing information. 感谢奥利弗·查尔斯沃思(Oliver Charlesworth)丢失的信息。

I really want to know that such comparator works with like quick sort or insertion sort (some famous comparison-based sorting algorithms) as topological sort. 我真的很想知道这样的比较器可以像快速排序或插入排序(某些著名的基于比较的排序算法)一样进行拓扑排序。

No, it is likely not to work. 不,它可能无法正常工作。 std::sort contract requires a strict weak ordering comparator; std::sort合约要求严格的弱比较器; violating it results in undefined behavior. 违反它会导致不确定的行为。 BTW, I've seen several times libstdc++ std::sort brutally crash (reading elements outside the container, IIRC) for this kind of comparator "relaxing". 顺便说一句,我已经多次看到libstdc ++ std::sort为这种比较器“松弛”而崩溃(读取容器外部的元素,IIRC)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM