C++20之飞船比较符<=> 强序,弱序,偏序

  1. std::tuple<>默认按顺序比较
  2. std::tie能把值引用打包
  3. C++20 <=>能按成员变量声明顺序比较
#include <iostream>
#include "common/log.h"
#include <limits>
#include <vector>
#include <span>
#include <array>
#include <type_traits>
#include <cmath>
#include <memory>
#include <variant>
using namespace AdsonLib;

struct Point1{
    int x;
    int y;
    friend bool operator==(const Point1 &a, const Point1 &b);
    friend bool operator<(const Point1 &a, const Point1 &b);
};

bool operator==(const Point1 &a, const Point1 &b) {
    return std::tie(a.x, a.y) == std::tie(b.x, b.y);
}
bool operator<(const Point1 &a, const Point1 &b) {
    return std::tie(a.x, a.y) < std::tie(b.x, b.y);
}

struct Point2{
    Point2(int a, int b):x(a), y(b){}
    virtual ~Point2(){}
    int x;
    int y;
    //默认比较,按成员定义顺序. 可以有虚函数
    friend auto operator<=>(const Point2 &a, const Point2 &b) = default; 
};


struct Point3{
    int x;
    int y;
    //默认比较,按成员定义顺序. 可以有虚函数
    friend auto operator<=>(const Point3 &a, const Point3 &b); 
};
auto operator<=>(const Point3 &a, const Point3 &b) {
    auto v1 = a.x * a.y;
    auto v2 = b.x * b.y;
    return v1 - v2;
}
//偏序(partial_ordering):不是任意两个可比较大小
//弱序(weak_ordering):任意两个可比较大小,但是相等定义为不大于也不小于
//强序(strong_ordering):任意两个可比较大小,也定义了相等比较
int main(int argc, char *argv[]) {
    std::tuple t1(0,3);
    std::tuple t2(0,2);
    auto t3 = std::tuple(4,5);
    auto b = (t1 <=> t3);
    Point2 p20{0,1};
    Point2 p21{0,2};
    LOG(INFO) << "cmp: " << (t1 < t2) << " <=> " << (p20 < p21);

    Point3 p30{4,1};
    Point3 p31{1,2};
    LOG(INFO) << (p30 > p31) << " <=> " << (p30 < p31);
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值