C++的string已经定义了各种比较运算符。
C风格的字符串(char数组)则采用strcmp比较字符串大小。详细见下
#include <cstdio> #include <algorithm> #include <cstring> using namespace std; // 先按成绩比较 // 成绩相同按名字, // 名字相同按年龄 struct Student { char name[101]; int age; int score; // ①const Student& 既可以持有常量也可以持有变量,持有变量时不改变。 // ②Class::fun() const 表示该函数不修改类对象,也就是不修改成员变量,如果改了,编译器报错。 bool operator < (const Student& b) const { if (score != b.score) return score < b.score; int tmp = strcmp(name, b.name); // ③strcmp 自左向右直到出现不同的字符或者‘\0‘ // 按ASCII值大小相比较,若s1=s2则返回0,s1<s2返回负数,s1>s2返回正数。 if (tmp != 0) return tmp < 0; else return age < b.age; } }; int main() { Student x = {"aaa", 18, 99}; Student y = {"bbb", 18, 99}; printf("%s\n", x < y ? "yes" : "no"); return 0; }
原文:https://www.cnblogs.com/xkxf/p/14442233.html