[C++] three-way comparison
Updated:
개요
- 3방향 비교 연산자
- 우주선 연산자(spaceship operator)라는 별명이 붙음
- ‘x <=> y’가 0보다 작으면 ‘x < y’, 크면 ‘x > y’, 같거나 동등하면 ‘x == y’
- 동등
- 가로가 2, 세로가 3인 직사각형과 가로가 3, 세로가 2인 직사각형은 서로 다르지만 넓이 기준으로는 동등
예제
- 코드
#include <compare> #include <cstring> #include <iostream> #include <string> using namespace std; template <typename T> constexpr string type_name() { const string s = __PRETTY_FUNCTION__; const int prefixSize = s.find("[with T = ") + strlen("[with T = "); return string(s.data() + prefixSize, s.find(';') - prefixSize); } class Square { private: int x; int y; public: Square(int x, int y) : x(x), y(y) {} int GetArea() const { return this->x * this->y; } weak_ordering operator<=>(const Square &s) const { return this->GetArea() <=> s.GetArea(); } }; int main() { cout << type_name<decltype(1 <=> 1)>() << endl; auto func = [](int x, int y) { if (x <=> y < 0) { cout << "x < y" << endl; } else if (x <=> y > 0) { cout << "x > y" << endl; } else { cout << "x == y" << endl; } }; func(1, 2); func(2, 1); func(1, 1); cout << "------" << endl; Square s1{1, 2}; Square s2{2, 1}; Square s3{3, 3}; // cout << s1 <=> s2 << endl; if (s1 <=> s2 == 0) { cout << "s1 <=> s2 == 0" << endl; } if (s1 <=> s3 < 0) { cout << "s1 <=> s3 < 0" << endl; } return 0; }
- 실행 결과
std::strong_ordering x < y x > y x == y