使用sort函數對結構體排序

在使用sort函數排序的時候,遇到了一些問題(因爲我們不只是排序數組呀)。

比如我們只想利用結構體變量中的其中一個變量來對結構體排序;(比如實際應用中對學生的成績排序並進行打印)

那麼經查閱,(簡單的方法)大致爲如下:

首先:sort函數的組成:

1、sort函數可以三個參數也可以兩個參數,必須的頭文件#include < algorithm>和using namespace std;
2、它使用的排序方法是類似於快排的方法,時間複雜度爲n*log2(n)

3、Sort函數有三個參數:(第三個參數可寫,可不寫)

(1)第一個是要排序的數組的起始地址。

(2)第二個是結束的地址(最後一位要排序的地址)

(3)第三個參數是排序的方法(一般爲一個函數),可以是從大到小也可是從小到大,還可以不寫第三個參數,此時默認的排序方法是從小到大排序

那麼,開始排序:

首先:寫一下結構體的組成吧。較爲簡單:

struct ss{
	int x;
	int y;
}; 

對於第三個參數,即排序方式,自然是需要設置的。如下幾種函數~~(其實是一種)~~均可:

bool cmp(struct ss c, struct ss d)
{
	if(c.y < d.y)
	{
		return true;
	}
	return false;
}
bool cmp(struct ss c, struct ss d)
{
	if(c.y < d.y)
	{
		return 1;
	}
	return 0;
}
int cmp(struct ss c, struct ss d)
{
	if(c.y < d.y)
	{
		return 1;
	}
	return 0;
}

那麼不妨測試一下:對第二個數據(y)排序升序(升降序通過第三個參數的符號即可):

測試數據:
8 15
20 130
120 3
150 2
110 7
180 1
50 8
200 0
140 3
120 2
測試代碼:
#include<bits/stdc++.h>
using namespace std;
struct ss{
	int x;
	int y;
}; 
bool cmp(struct ss c, struct ss d)
{
	if(c.y < d.y)
	{
		return true;
	}
	return false;
}
int main() {
	int i,n,a,b,s,sum=0;
	cin>>n>>s>>a>>b;
	
	struct ss apple[n];
	
	for(i=0;i<n;i++)
	cin>>apple[i].x>>apple[i].y;
	sort(apple,apple+n-1,cmp);//對結構體排序 
    cout<<apple[0].x<<"  "<<apple[0].y;
    return 0;
}
測試結果:120 0
發佈了24 篇原創文章 · 獲贊 7 · 訪問量 6825
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章