01串排序
将01串首先按长度排序,长度相同时,按1的个数多少进行排序,1的个数相同时再按ASCI码值排序。输入数据中含有一些01串,01串的长度不大于256个字符。重新排列01串的顺序。使得串按基本猫述的方式排序。
#include <iostream> #include <vector> #include <algorithm> #include <string> using namespace std; class String { public: string str; String(const string& s) : str(s) {} int le() const { return str.length(); } int count1() const { return count(str.begin(), str.end(), '1'); } bool operator<(const String& other) const { if (le() != other.le()) { return le() < other.le(); } if (count1() != other.count1()) { return count1() < other.count1(); } return str < other.str; } }; struct Str { 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(), Str()); for (const auto& bs : Strings) { cout << bs.str << 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 a; cin >> a; for (int c = 1; c <= a; ++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 < a) { cout << endl; } } return 0; }
运行结果: