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

猜你喜欢

转载自blog.csdn.net/wyg_031113/article/details/128298902
今日推荐