快速排序c++对结构排序_用C ++对结构进行排序

快速排序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++对结构排序

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值