Sort by an element in the structure ()

 

Today, when writing Kruskal's algorithm, I encountered a problem, that is, how to quickly sort the structure of Edge by weight. The structure is as follows:

 

struct Edge {
 int vex1;   //起点
 int vex2;   //终点
 int weight; //权重
};

 

After Baidu found #include<algorithm>that there is a sortfunction in the header file , which contains three parameters

 

  1. The first is the starting address of the array to be sorted
  2. The second is the ending address (the address next to the address of the last digit to be sorted)
  3. The third parameter is the sorting method, which can be from largest to smallest or from smallest to largest, or not to write the third parameter. At this time, the default sorting method is from smallest to largest.

 

In my question, just create vector<Edge>and customize the sorting method, it's ok. Post the relevant code below:

 

/*
自定义排序函数
*/
bool compare(const Edge &e1, const Edge &e2) {	
	 return e1.weight < e2.weight;  //权重从小到大排序
}
------------------------分割线
sort(e.begin(), e.end(), compare);  //按边的权值从小到大排序

Example: Sort by average score

#include<iostream>
#include<cstdio>
#include<cstring>
#include<algorithm>
#include<cmath>
typedef long long LL ;
using namespace std;

int n;
struct stu
{
    int num;
    int x1;
    int x2;
    int x3;
    double res; //均分
};

struct stu s[510];
bool compare(const stu &s1,const stu &s2) //按均分排序
{
    return s1.res >s2.res;
}

int main()
{
    while(cin>>n)
    {
        for(int i=0;i<n;i++)
            cin>>s[i].num>>s[i].x1>>s[i].x2>>s[i].x3;
        for(int i=0;i<n;i++)  //计算均分
        {
            s[i].res=0.4*s[i].x1+0.35*s[i].x2+0.25*s[i].x3;
        }
        sort(s,s+n,compare);

        for(int i=0;i<3;i++) //输出学号与均分
            printf("%d %.1lf\n",s[i].num,s[i].res);
    }

    
    getchar();getchar();
	return 0;
}


Reference: https://blog.csdn.net/weixin_43189363/article/details/89893160

Guess you like

Origin blog.csdn.net/weixin_44026026/article/details/110305910