c++結(jié)構(gòu)體排序方式(1條件,多條件)
c++結(jié)構(gòu)體排序(1條件,多條件)
最近做題的時候總會遇到排序問題,同樣一個問題用結(jié)構(gòu)體排序和用數(shù)組做差的不僅僅是代碼的長度,還有理解的難易程度,很明顯,用結(jié)構(gòu)體排序更簡單易懂。
但結(jié)構(gòu)體不能直接用algorithm頭文件里的sort函數(shù),需要我們自己補充一個函數(shù)。這里就給大家一一列舉出來。
一個判斷條件
#include<iostream> #include<algorithm> #include<string> using namespace std; struct cj { int num; string name; int score; }; bool cmp(cj a,cj b) { return a.score>b.score; } int main() { cj x[5]; //這里的5可以手動輸入n代替 for(int i=0;i<5;i++) cin>>x[i].name>>x[i].score>>x[i].num; sort(x,x+5,cmp); cout<<'\n'; for(int i=0;i<5;i++) cout<<x[i].name<<'\t'<< x[i].score<<'\t'<<x[i].num<<'\n'; system("pause"); return 0; }
這里的判斷條件為score,效果如圖
多個判斷條件(以兩個為例)
還是以上的代碼,只要把cmp函數(shù)稍做修改就可以了。這里我們的第二給判斷條件為num.
bool cmp(cj a,cj b) { if(a.score!=b.score) return a.score>b.score; else return a.num>b.num; }
效果如圖
有更多條件也可以仿照兩個條件的進行修改,要強調(diào)的是,多個條件中,越靠前的所起作用越大。
這里對于初學(xué)者不一定要懂為什么要這樣寫,只需要會用就好了。等到熟練之時可以再找資料更深層次地理解。有什么問題歡迎在評論區(qū)與我交流。
C++結(jié)構(gòu)體自定義排序
聲明:本機無C++環(huán)境,以下代碼均沒有編譯測試,最近golang寫的比較多,語法可能會有問題,請自行測試代碼
sort排序函數(shù)簡單使用
#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); //默認(rèn)從小到大排序 */ /* 0 到 n-1 輸入 for(int i=0;i<n;i++) scanf("%d",&a[i]); sort(a,a+n); */ //從大到小排序需要寫自定義優(yōu)先級函數(shù) sort(a,a+n,cmp1); //采用cmp1函數(shù)排序 從大到小 sort(a,a+n,cmp2); //采用cmp2函數(shù)排序 從小到大 return 0; }
結(jié)構(gòu)體的自定義排序
例如 對于時間排序 年月日
#include <bits/stdc++.h> using namespace std; /* //結(jié)構(gòu)體排序兩種寫法 寫法1 結(jié)構(gòu)體內(nèi)部 重載<運算符 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 { //重載<函數(shù) 內(nèi)部寫小于邏輯 if (year == p.year && month == p.month) { return day < p.day; } if (year == p.year) { return year < p.year; } return year < p.year; } }; //寫法2 定義結(jié)構(gòu)體后 寫自定義排序函數(shù) 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) { //語句不同 實現(xiàn)排序效果同方法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; }
總結(jié)
以上為個人經(jīng)驗,希望能給大家一個參考,也希望大家多多支持腳本之家。
相關(guān)文章
c語言同名標(biāo)靶點自動匹配算法實現(xiàn)實例代碼
這篇文章主要介紹了c語言同名標(biāo)靶點自動匹配算法實現(xiàn)實例代碼,分享了相關(guān)代碼示例,小編覺得還是挺不錯的,具有一定借鑒價值,需要的朋友可以參考下2018-02-02