본문 바로가기
C++/C++ 기초 문법

[C++] 3방향 비교 연산자

by 후야- 2023. 12. 26.

1. 3방향 비교 연산자

-> 3방향 비교 연산자는 두 값으 순서를 결정하는 데 사용한다.

-> 연산자 기호는 <=> 로 우주선처럼 생겼다고해서 우주선 연산자라고도 부른다

 

 

◾ 피연산자가 정수 타입이면 강한 순서라고 부른다.

strong_ordering::less     = 첫 번째 피연산자가 두 번째 피연산자보다 작을 때
strong_ordering::greater  = 첫 번째 피연산자가 두 번째 피연산자보다 클 때 
strong_ordering::equal    = 두 피연산자가 같을 때

 


◾ 부동소수점 타입이라면 부분 순서라고 부른다.

partial_ordering::less       = 첫 번째 피연산자가 두 번째 피연산자보다 작을 때
partial_ordering::greater    = 첫 번째 피연산자가 두 번째 피연산자보다 클 때
partial_ordering::equivalent = 두 피연산자가 같다.
partial_ordering::unordered  = 두 피연산자 중 하나는 숫자가 아니다.

자신이 직접 정의한 타입에 대해 3방향 비교 연산을 구현할 때 약한 순서라고 부른다.

week_ordering::less        = 첫 번째 피연산자가 두 번째 피연산자보다 작을 때
weak_ordering::greater     = 첫 번째 피연산자가 두 번째 피연산자보다 클 때
weak_ordering::equivalent  = 두 피연산자가 같다.

 

ex)

#include <iostream>
#include <format>

using namespace std;

int main()
{
	int i{ 0 };
	strong_ordering result{ i <=> 0 };
	if (result == strong_ordering::less) { cout << "less" << endl; };
	if (result == strong_ordering::greater) { cout << "greater" << endl; };
	if (result == strong_ordering::equal) { cout << "equal" << endl; };

	return 0;
}

-> i 가 0 보다 작으면 less, 크면 greater, 같으면 equal 뜬다.


 

◾ 이름 있는 비교 함수

#include <iostream>
#include <format>

using namespace std;

int main()
{
	int i{ 0 };
	strong_ordering result{ i <=> 0 };
	if (is_lt(result)) { cout << "less" << endl; };
	if (is_gt(result)) { cout << "greater" << endl; };
	if (is_eq(result)) { cout << "equal" << endl; };

	return 0;
}