C++重載<運算符
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; }
排序結構體方法一:重載<運算符
#include <cstdio> #include <algorithm> #include <cstring> using namespace std; struct StructName { int index1; int index2; bool operator < (const StructName& b) const { if (index1 != b.index1) return index1 < b.index1; else return index2 < b.index2; } } buf[5]; void printBuf() { for (int i = 0; i != 5; ++i) { printf("%d %d\n", buf[i].index1, buf[i].index2); } } int main() { buf[0] = {3, 3}; buf[1] = {3, 2}; buf[2] = {2, 3}; buf[3] = {3, 1}; buf[4] = {7, 3}; sort(buf, buf + 5); printBuf(); return 0; }
排序結構體方法二:自定義cmp函數
#include <cstdio> #include <algorithm> #include <cstring> using namespace std; struct StructName { int index1; int index2; } buf[5]; void printBuf() { for (int i = 0; i != 5; ++i) { printf("%d %d\n", buf[i].index1, buf[i].index2); } } bool cmp(const StructName& a, const StructName& b) { if (a.index1 != b.index1) return a.index1 < b.index1; else return a.index2 < b.index2; } int main() { buf[0] = {3, 3}; buf[1] = {3, 2}; buf[2] = {2, 3}; buf[3] = {3, 1}; buf[4] = {7, 3}; sort(buf, buf + 5, cmp); printBuf(); return 0; }