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;
}

int 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
*/

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章