C++ 对一个结构体的集合进行排序,需要的代码
/*
4 50
10 60
20 100
30 120
16 45
*/
#define _CRT_SECURE_NO_WARNINGS#include <iostream>
#include<vector>
#include <algorithm> // 需要包含 sort() 函数所在的头文件
struct P {int w;//重量int v;//总价值float s;P(int w, int v) {this->w = w;this->v = v;s = 1.0f * v / w;}
};
using namespace std;bool cmp(const P& a, const P& b) {return a.s > b.s; // 按照 s 成员变量从大到小排序
}int main() {int n, w;cin >> n >> w;vector<P> v;for (int i = 0; i < n; i++) {int a, b;cin >> a >> b;P p(a,b);v.push_back(p);}sort(v.begin(), v.end(), cmp); // 对 v 向量按照 s 成员变量从大到小排序for (auto i : v) {cout << i.w << " " << i.v << " " << i.s << endl;}return 0;
}