C++結構體自定義排序

聲明:本機無C++環境,以下代碼均沒有編譯測試,最近golang寫的比較多,語法可能會有問題,請自行測試代碼

sort排序函數簡單使用 

#include <bits/stdc++.h>
using namespace std;
int a[100];
bool cmp1(int x,int y) {
	return x > y;
}
bool cmp2(int x,int y) {
	return x < y;
}
int main()
{
	//sort簡單用法
	int n;
	scanf("%d",&n);
	/*
	1到n輸入
	for(int i=1;i<=n;i++)
		scanf("%d",&a[i]);
	sort(a+1,a+1+n); //默認從小到大排序
	*/
	/*
	0 到 n-1 輸入 
	for(int i=0;i<n;i++)
		scanf("%d",&a[i]);
	sort(a,a+n);
	*/
	//從大到小排序需要寫自定義優先級函數
	sort(a,a+n,cmp1); //採用cmp1函數排序 從大到小
	sort(a,a+n,cmp2); //採用cmp2函數排序 從小到大
   return 0;
}

結構體的自定義排序

例如 對於時間排序 年月日

#include <bits/stdc++.h>
using namespace std;
/*
//結構體排序兩種寫法 寫法1 結構體內部 重載<運算符
struct node {
	int year,month,day;
	node() {year=0,month=0,day=0;}
	node(int y,int m,int d) { year=y,month=m,day=d;}
	bool operator< (const node &p) const { //重載<函數 內部寫小於邏輯
		if (year == p.year && month == p.month) {
			return day < p.day;
		}
		if (year == p.year) {
			return year < p.year;
		}
		return year < p.year;
	}
};
//寫法2 定義結構體後 寫自定義排序函數
struct node {
	int year,month,day;
	node() {year=0,month=0,day=0;}
	node(int y,int m,int d) { year=y,month=m,day=d;}
};
bool cmp(const node &p,const node &q) { //語句不同 實現排序效果同方法1 const不可省略
	if (p.year != q.year) return p.year < q.year;
	if (p.month != q.month) return p.month < q.month;
	return p.day < q.day;
}
*/

node t[100];
int main()
{
	t[0] = node{2019,1,20};
	t[1] = node{2019,1,22};
	t[2] = node{2018,2,1};
	t[3] = node{2020,1,1};
	/* 方法1
	sort(t,t+4);
	方法2
	sort(t,t+4,cmp);
	*/
	for (int i=0;i<4;i++) {
	    printf("%d %d %d\n",t[i].year,t[i].month,t[i].day);
	}
   return 0;
}

 

發佈了146 篇原創文章 · 獲贊 14 · 訪問量 3萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章