今天碰到的std::sort 的宕机

http://www.sgi.com/tech/stl/StrictWeakOrdering.html

最主要的就是,保证自己的compare函数,满足下面的条件


Irreflexivityf(x, x) must be false.
Antisymmetryf(x, y) implies !f(y, x)
Transitivityf(x, y) and f(y, z) imply f(x, z).
Transitivity of equivalenceEquivalence (as defined above) is transitive: if x is equivalent to y and y is equivalent to z, then x is equivalent to z. (This implies that equivalence does in fact satisfy the mathematical definition of an equivalence relation.)

简单的就是 a=b, return false 

如果a < b 那么b < a 一定是false,


在library文档中提及到定义的函数必须是 strict wak ordering 。网上找的,就是下面的意思

Strict: pred (X, X) is always false.

Weak: If ! pred (X, Y) && !pred (Y, X), X==Y.

Ordering: If pred (X, Y) && pred (Y, Z), then pred (X, Z).

`std::sort`是C++标准库中的一个函数模板,主要用于对容器中的元素进行排序。然而,它不能直接用来排序`std::map`。原因在于`std::map`本身是一种基于键值对的容器,并且它默认按照键的顺序存储元素,也就是说`std::map`内部就是有序的。`std::map`的排序规则是基于其键的比较函数`std::less`,或者是用户定义的比较函数。 如果要使用`std::sort`来对`std::map`中的元素进行排序,你需要先将`std::map`中的元素复制到一个可以排序的容器中,比如`std::vector`,然后使用`std::sort`对这个容器进行排序。排序后,你可以将排序后的元素再复制回`std::map`(如果需要的话),但这样做通常没有太大的实际意义,因为`std::map`的有序特性在操作完成后可能会被破坏。 如果你想要在遍历`std::map`时按照特定的顺序输出元素,可以通过对`std::map`的迭代器进行排序来实现。例如,如果你想根据键的值进行升序排序,可以直接使用默认的`std::less`比较函数: ```cpp #include <iostream> #include <map> #include <vector> #include <algorithm> // for std::sort int main() { std::map<int, int> m = {{3, 1}, {1, 2}, {2, 3}}; // 将map的键值对复制到vector中 std::vector<std::pair<int, int>> v(m.begin(), m.end()); // 使用默认的比较函数std::less对vector进行排序 std::sort(v.begin(), v.end()); // 输出排序后的元素 for (const auto& p : v) { std::cout << p.first << ": " << p.second << std::endl; } return 0; } ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值