C++中的结构体排序

最近在上算法课程,老师要求用C++来做,刚好软件开发选的也是C++(虽然自己选的方向是Java)。
做题的过程中才发现自己其实基础并不是很牢固,故记录一下。

C++结构体

格式:

1
struct Example{
	int a;
};

struct是结构体的关键字,Example相当于结构体的一个主体,定义变量可以如下:

Example exam;
2
typedef struct{
	int a;
}Example;

这里跟第一个是一样的

3
struct Example{
	int a
}exam;

这里在定义结构体的时候就定义了变量。

结构体的排序

直接上代码:

#include <iostream>
#include <vector>
#include <algorithm>

using namespace std;

struct example {
	double a,h;
};

bool comparison(example a, example b) {
	return a.h < b.h;// <表示升序,>表示降序
}

void mysort(vector<example>& exam) {
	sort(exam.begin(), exam.end(), comparison);
}

int main() {
	int number;
	cin >> number;
	vector<example> exam(number);
	double a, h;
	for (int i = 0; i < number; i++) {
		cin >> a >> h;
		exam[i].a = a;
		exam[i].h = h;
	}
	mysort(exam);
	for (int i = 0; i < exam.size(); i++) {
		cout << exam[i].a << " " << exam[i].h << endl;
	}
	return 0;
}
  • 1
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值