01串排序
#include <iostream>
#include <vector>
#include <algorithm>
#include <string>
using namespace std;
class String {
public:string str; String(const string& s) : str(s) {} int length() const {return str.length();}int countOnes() const {return count(str.begin(), str.end(), '1');}bool operator<(const String& other) const {if (length() != other.length()) {return length() < other.length(); }if (countOnes() != other.countOnes()) {return countOnes() < other.countOnes(); }return str < other.str; }
};
struct StringComparator {bool operator()(const String& a, const String& b) {return a < b;}
};
int main() {vector<String> Strings;string s;while (getline(cin, s)) {Strings.emplace_back(s);if (s == "")break;}sort(Strings.begin(), Strings.end(), StringComparator());for (const auto& bs : Strings) {std::cout << bs.str << std::endl;}return 0;
}
运行结果:
按绩点排名
#include <iostream>
#include <vector>
#include <algorithm>
#include <iomanip>
#include <string>
using namespace std;
class Student {
public:string name;double gpa;Student(string n, double g) : name(n), gpa(g) {} bool operator<(const Student& other) const {if (gpa != other.gpa) {return gpa > other.gpa; }else {return name < other.name; }}
};
int main() {int classCount;cin >> classCount;for (int c = 1; c <= classCount; ++c) {int n, m;cin >> n;vector<int> credits(n);for (int i = 0; i < n; ++i) {cin >> credits[i];}cin >> m;vector<Student> students;for (int i = 0; i < m; ++i) {string name;vector<int> scores(n);cin >> name;for (int j = 0; j < n; ++j) {cin >> scores[j];}double gpa = 0.0;for (int j = 0; j < n; ++j) {if (scores[j] >= 60) {gpa += (scores[j] - 50.0) / 10.0 * credits[j];}}gpa /= 10.0;students.emplace_back(name, gpa);} sort(students.begin(), students.end()); cout << "class " << c << ":" << endl;for (const auto& student : students) {cout << left << setw(10) << student.name << " " << fixed << setprecision(2) << student.gpa << endl;}if (c < classCount) {cout << endl; }}return 0;
}
运行结果: