📜  3路运算符(空间船只运营)的C ++ 20

📅  最后修改于: 2021-05-31 20:30:02             🧑  作者: Mango

三路比较运算符“<=>”被称为飞船运算符。太空船运算符确定两个对象ABA B。太空船运算符或编译器可以为我们自动生成。同样,三向比较是一种可以在一个查询中给出整个关系的函数。传统上,strcmp()就是这样的一个函数。给定两个字符串,它将返回一个整数,其中

  • <0表示第一个字符串小于
  • == 0如果两者相等
  • 如果第一个字符串较大,则> 0。

它可以给出三个结果之一,因此是三向比较。

Equality Ordering
Primary == <=>
Secondary != <, >, <=, >=

从上表可以看出,宇宙飞船运算符是主要运算符,即可以颠倒,可以用它写出相应的次要运算符。

程序1

下面是三路运算符两个浮点型变量的实现:

C++
// C++ 20 program to illustrate the
// 3 way comparison operator
#include 
using namespace std;
  
// Driver Code
int main()
{
    float A = -0.0;
    float B = 0.0;
  
    // Find the value of 3 way comparison
    auto ans = A <= > B;
  
    // If ans is less than zero
    if (ans < 0)
        cout << "-0 is less than 0";
  
    // If ans is equal to zero
    else if (ans == 0)
        cout << "-0 and 0 are equal";
  
    // If ans is greater than zero
    else if (ans > 0)
        cout << "-0 is greater than 0";
  
    return 0;
}


C++
// C++ 20 program for the illustration of the
// 3-way comparison operator for 2 vectors
#include 
using namespace std;
  
// Driver Code
int main()
{
    // Given vectors
    vector v1{ 3, 6, 9 };
    vector v2{ 3, 6, 9 };
  
    auto ans2 = v1 <= > v2;
  
    // If ans is less than zero
    if (ans2 < 0) {
  
        cout << "v1 < v2" << endl;
    }
  
    // If ans is equal to zero
    else if (ans2 == 0) {
  
        cout << "v1 == v2" << endl;
    }
  
    // If ans is greater than zero
    else if (ans2 > 0) {
  
        cout << "v1 > v2" << endl;
    }
  
    return 0;
}


输出:

程序2

下面是三路运算符两个向量执行:

C++

// C++ 20 program for the illustration of the
// 3-way comparison operator for 2 vectors
#include 
using namespace std;
  
// Driver Code
int main()
{
    // Given vectors
    vector v1{ 3, 6, 9 };
    vector v2{ 3, 6, 9 };
  
    auto ans2 = v1 <= > v2;
  
    // If ans is less than zero
    if (ans2 < 0) {
  
        cout << "v1 < v2" << endl;
    }
  
    // If ans is equal to zero
    else if (ans2 == 0) {
  
        cout << "v1 == v2" << endl;
    }
  
    // If ans is greater than zero
    else if (ans2 > 0) {
  
        cout << "v1 > v2" << endl;
    }
  
    return 0;
}

输出:

注意:您应该下载足够的最新编译器以运行C++ 20。

太空飞船运营商的需求

  • 它的所有其他运算符的共同泛化(对于完全有序结构域):>,> =,==,<=,<。使用<=>,每个操作可以在一个完全通用的方式在用户定义的数据类型的类似,其中一个具有以定义其他6运算符逐个代替的结构的情况下实现。
  • 对于字符串,它等效于C标准库的旧strcmp()函数。因此,对于字典顺序检查(例如矢量或列表中的数据或其他有序容器中的数据)很有用。
要从最佳影片策划和实践问题去学习,检查了C++基础课程为基础,以先进的C++和C++ STL课程基础加上STL。要完成从学习语言到DS Algo等的更多准备工作,请参阅“完整面试准备课程”