STL--自定义类型的排序
2024-08-30 01:01:06
STL的排序太坑了,尤其是在VS2010上重载sort函数的第三个比较参数的时候。
invalid operator <
这个错在写多关键字排序的时候就没有停止过。
本来想查书解决,结果各种重载都试了还是不行,百度才知道是因为:strict weak ordering。也就是说,如果a==b,则返回的应该是false,如果返回的是true,则会出上面的错。
所以最简单的这种比较函数:无论相等或者不等都返回1的写法
bool comp(Student s1, Student s2){
if(s1.score==s2.score)
return 1;
else
return s1.id<s2.id;
} bool comp(Student s1, Student s2){
if(s1.score!=s2.score)
return 1;
else
return s1.id<s2.id;
}
这两种写法都会报错。
而无论相等或者不等都返回0的写法不会报错
bool comp(Student s1, Student s2){
if(s1.score==s2.score)
return 0;
else
return s1.id<s2.id;
}
bool comp(Student s1, Student s2){
if(s1.score!=s2.score)
return 0;
else
return s1.id<s2.id;
}
故多关键字的STL排序可以写成:
#include<time.h>
#include<iostream>
#include<vector>
#include<algorithm>
using namespace std;
struct Node
{
int x;
int y; };
bool Comp(Node &a,Node &b)
{
if(a.x==b.x) return b.y>a.y;
else
return a.x>b.x;
}
vector<Node> node;
int main()
{
srand((unsigned int)time(0));
for(int i=0;i<10;i++)
{
Node a;
a.x=rand()%(10+1-0)+0;
a.y=rand()%(10+1-0)+0;
node.push_back(a);
}
sort(node.begin(),node.end(),Comp);
for(int i=0;i<10;i++)
{
printf("%d %d\n",node[i].x,node[i].y);
}
}
---上面是标准的写法...
最新文章
- 提高安全性而在HTTP响应头中可以使用的各种响应头字段
- Java NIO服务器端开发
- iOS— UIScrollView和 UIPageControl之间的那些事
- 【codevs 1296】营业额统计 水~~
- ACM之Java速成(2)
- C++除法取整
- 开通博客第一天 (先发一些android(java)常见异常信息
- 前端要怎么学createjs!!!???
- Android 4.4 Kitkat Phone工作流程浅析(六)__InCallActivity显示更新流程
- Ubuntu 14.04安装Sogou输入法
- C# .NET更智能的数据库操作的封装完整版(重构)
- Progressive Web Applications
- zabbix源码安装实例
- SWPU-ACM集训队周赛之组队赛(3-11)G题题解
- Linux kernel engineer--trace
- 深入学习Motan系列(二)——服务发布
- MySQL数据库order by 奇慢无比
- BZOJ1855或洛谷2569 [SCOI2010]股票交易
- opencv实现canopy算法
- IBM Personal Communications 软件:精简绿色版TN3270终端模拟器:经测试可以在 (winxp、win2003、win764)上运行
热门文章
- poj3660 Cow Contest(Floyd-Warshall方法求有向图的传递闭包)
- 如何在ANDROID JNI 的C++中打Log
- Git和CocoaPods的简单使用
- 关于XML与类型Class的映射
- Php 的替代语法
- selenium自动化测试(1):环境搭建
- C#基础(七)——静态类与非静态类、静态成员的区别
- [C#]将千分位字符串转换成数字
- Starting MySQL.. ERROR! The server quit without updating PID file (/usr/local/mysql/data/localhost.localdomain.pid).
- Python数据结构——散列表