三向比较运算符<=>

        三向比较符又称太空飞船操作符,可以用来确定一个值和另外一个值的大小关系,返回枚举类型,定义在<compare>头文件中。

例1:

int n1{ 10 };
int n2{ 20 };
auto result = n1 <=> n2;
if (std::strong_ordering::less == result) //判断n1是否小于n2
{
	cout << "n1 < n2" << endl;
}

if (std::strong_ordering::greater == result) //判断n1是否大于n2
{
	cout << "n1 > n2" << endl;
}

if (std::strong_ordering::equal == result) //判断n1是否等于n2
{
	cout << "n1 = n2" << endl;
}

if (std::strong_ordering::equivalent == result) //判断n1是有与n2等价
{
	cout << "n1 == n2" << endl;
}


//输出结果:n1<n2	

        result的类型为一个名为std::strong_ordering的枚举类型,因为n1 n2均为int,则该比较的结果为强排序,其中equal意为相等,equivalent意为等价,在strong ordering类型下这两个意思相同,以下是这两个值得源码定义:

…
enum class _Compare_eq : _Compare_t { equal = 0, equivalent = equal };
…
inline constexpr strong_ordering strong_ordering::equal{static_cast<_Compare_t>(_Compare_eq::equal)};
inline constexpr strong_ordering strong_ordering::equivalent{static_cast<_Compare_t>(_Compare_eq::equivalent)};
…

可见在源码层次,这两个值是完全一样的。

例2:

如果比较的类型是浮点型,那么返回的结果就是partial ordering

    double n1{ 10 };
	double n2{ 20 };
	auto result = n1 <=> n2;
	if (std::partial_ordering::less == result) //判断n1是否小于n2
	{
		cout << "n1 < n2" << endl;
	}

	if (std::partial_ordering::greater == result) //判断n1是否大于n2
	{
		cout << "n1 > n2" << endl;
	}

	if (std::partial_ordering::equivalent == result) //判断n1是否等于n2
	{
		cout << "n1 = n2" << endl;
	}
	if (std::partial_ordering::unordered == result) //
	{
		cout << "n1 or n2 is unordered" << endl;
	}
	//输出结果:n1<n2

例3:

对于自定义类型重载<=>我们需要弱排序weak_ordering

import <iostream>;
import <string>;
import <compare>;
using namespace std;

class testWeakOrdering
{
public:
	testWeakOrdering(int value):m_value(value)
	{

	}
	std::weak_ordering operator<=> (const testWeakOrdering& other)
	{
		if (m_value < other.m_value)
		{
			return weak_ordering::less;
		}
		else if (m_value == other.m_value)
		{
			return weak_ordering::equivalent;
		}
		else
		{
			return weak_ordering::greater;
		}
	}

private:
	int m_value;
};

int main()
{
	testWeakOrdering n1{ 10 };
	testWeakOrdering n2{ 20 };
	auto result = n1 <=> n2;
	if (std::weak_ordering::less == result) //判断n1是否小于n2
	{
		cout << "n1 < n2" << endl;
	}

	if (std::weak_ordering::greater == result) //判断n1是否大于n2
	{
		cout << "n1 > n2" << endl;
	}

	if (std::weak_ordering::equivalent == result) //判断n1是否等于n2
	{
		cout << "n1 = n2" << endl;
	}

	return 0;
}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值