C++ sort用法

#include <iostream>
#include <string>
#include <sstream>
#include <algorithm>
using namespace std;

//第一种方法是重载小于运算符
//sort(begin, end, sort_type),(起始地址,结束地址,排序方式),begin和end是左闭右开。
struct Point{
	int a,b;
	Point(int a=0, int b=0){this->a=a; this->b=b;}
	bool operator < (const Point &tmp){
		return this->a < tmp.a || (this->a == tmp.a && this->b < tmp.b) ? true : false;
	}
};

ostream& operator << (ostream &out, const Point &tmp){
	out<<"("<<tmp.a<<", "<<tmp.b<<")";
	return out;
}

int main(){
	Point a[] = {Point(2,2), Point(2,1), Point(1,2), Point(1,1)};
	sort(a,a+4);
	for(int i=0;i<4;i++)
		cout<<a[i]<<" ";
	cout<<endl<<"hello,world"<<endl;
	return 0;
}

/*
C:\Users\kepcum\Desktop>g++ test.cpp -o test.exe

C:\Users\kepcum\Desktop>test.exe
(1, 1) (1, 2) (2, 1) (2, 2)
hello,world
*/
#include <iostream>
#include <string>
#include <sstream>
#include <algorithm>
using namespace std;

//第二种方法是自己写比较函数cmp,返回值是int
//sort(begin, end, sort_type),(起始地址,结束地址,排序方式),begin和end是左闭右开。
struct Point{
	int a,b;
	Point(int a=0, int b=0){this->a=a; this->b=b;}
};

ostream& operator << (ostream &out, const Point &tmp){
	out<<"("<<tmp.a<<", "<<tmp.b<<")";
	return out;
}

bool cmp(const Point &x, const Point &y){
	return x.a-y.a ? x.a<y.a : x.b<y.b;
}
int main(){
	Point a[] = {Point(2,2), Point(2,1), Point(1,2), Point(1,1)};
	sort(a,a+4,cmp);
	for(int i=0;i<4;i++)
		cout<<a[i]<<" ";
	cout<<endl<<"hello,world"<<endl;
	return 0;
}

/*
C:\Users\kepcum\Desktop>g++ test.cpp -o test.exe

C:\Users\kepcum\Desktop>test.exe
(1, 1) (1, 2) (2, 1) (2, 2)
hello,world
*/

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值