📜  C++中STL数组上的关系运算符

📅  最后修改于: 2021-05-30 14:45:42             🧑  作者: Mango

本文说明了数组STL上不同关系运算符的工作方式。相等性比较(==)通过使用运算符(==)依次比较元素来执行,并在第一个不匹配处停止。
小于比较(<)大于比较(>)的行为就像使用lexicographical_compare算法一样,该算法使用倒数方式依次使用运算符()来比较元素(即,检查a 数组上关系运算符的实现帮助我们在存储在不同数组中的数据之间进行比较。

等效运算符:这是一些工作相同的运算符。

(a != b) is equivalent to !(a == b)
  (a > b) equivalent to (b < a)
  (a <= b) equivalent to !(b < a)  

时间复杂度:上面操作的时间复杂度为O(n) ,其中n是数组的大小。

下面的代码说明了关系运算符在数组上的工作方式

程序1:关系运算符比较

// array comparisons using relational operators
#include 
using namespace std;
  
int main()
{
    // declaration of array
    array a = { 1, 2, 3, 4, 5 };
    array b = { 1, 2, 3, 4, 5 };
    array c = { 5, 4, 3, 2, 1 };
  
    if (a >= b) {
        cout << "a is greater than equal to b\n";
    }
    else {
        cout << "a is neither greater than nor equal to b\n";
    }
  
    if (b < c) {
        cout << "b is less than c\n";
    }
    else {
        cout << "b is not lesser than c\n";
    }
    if (a >= c) {
        cout << "a is greater than equal to c\n";
    }
    else {
        cout << "a is neither greater than nor equal to c\n";
    }
  
    return 0;
}

输出 :

a is greater than equal to b
b is less than c
a is neither greater than nor equal to c

计划2:关系算符平等

// CPP program to check for array qualities.
#include 
using namespace std;
  
int main()
{
    // declaration of array
    array a = { 'a', 'b', 'c', 'd', 'e' };
    array b = { 'e', 'd', 'c', 'b', 'a' };
    array c = { 'a', 'b', 'c', 'd', 'e' };
  
    if (a == b) {
        cout << "a is  equal to b\n";
    }
    else {
        cout << "a is not equal to b\n";
    }
  
    if (b != c) {
        cout << "b is not equal to c\n";
    }
    else {
        cout << "b is equal to c\n";
    }
    if (a == c) {
        cout << "a is equal to c\n";
    }
    else {
        cout << "a is not equal to c\n";
    }
  
    return 0;
}

输出 :

a is not equal to b
b is not equal to c
a is equal to c
要从最佳影片策划和实践问题去学习,检查了C++基础课程为基础,以先进的C++和C++ STL课程基础加上STL。要完成从学习语言到DS Algo等的更多准备工作,请参阅“完整面试准备课程”