C++重载<运算符及排序结构体

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;
}

 

posted @ 2021-02-24 16:34  xkfx  阅读(1539)  评论(0)    收藏  举报