快速排序c++对结构排序
Generally sorting is done on an array of integer or string but there may be a situation where sorting is based on the number but actual data may be some other value.
通常,排序是在整数或字符串数组上进行的,但有时会基于数字进行排序,但实际数据可能是其他某个值。
Example:
例:
Suppose we have to sort names of student according to roll number. So a structure can be created which can be used to store roll number and names.
假设我们必须根据卷号对学生的姓名进行排序。 因此,可以创建一个结构,该结构可用于存储卷编号和名称。
Declaration of structure:
结构声明:
typedef struct value{
int roll;
string name;
}data;
C++ Code to sort structure:
C ++代码排序结构:
#include <bits/stdc++.h>
using namespace std;
typedef struct value{
int roll;
string name;
}data;
bool compare(data a, data b)
{
//for descending order replace with a.roll >b.roll
if(a.roll < b.roll)
return 1;
else
return 0;
}
int main()
{
int n,i;
cout<<"Enter the number of students\n";
cin>>n;
data array[n];//array of structure is created
cout<<"Enter roll number and then name\n";
for(i=0;i<n;i++)
{
cin>>array[i].roll;
cin>>array[i].name;
}
sort(array,array+n,compare);
cout<<"Sorted list..."<<endl;
for(i=0;i<n;i++)
{
cout<<array[i].roll<<" ";
cout<<array[i].name<<endl;
}
return 0;
}
Output
输出量
Enter the number of students
3
Enter roll number and then name
101 Amit
102 Abhishek
103 Shubham
Sorted list...
101 Amit
102 Abhishek
103 Shubham
翻译自: https://www.includehelp.com/cpp-programs/sorting-a-structure-in-cpp.aspx
快速排序c++对结构排序