C++ vector::operator<=() 函式



C++ vector::operator<=() 函式用於測試第一個向量是否小於或等於另一個向量,如果運算子左側小於或等於向量右側的向量,則返回 true,否則返回 false。運算子 <= 按順序比較元素,並在第一次不匹配時停止比較。此成員函式永遠不會丟擲異常,並且 operator<=() 函式的時間複雜度為線性。

語法

以下是 C++ vector::operator<=() 函式的語法:

bool operator<=(const vector<Type, Allocator>& left, const vector<Type, Allocator>& right);

引數

  • left - 表示運算子左側的向量物件型別。
  • right - 表示運算子右側的向量物件型別。

示例 1

讓我們考慮以下示例,我們將使用 opertor<=() 函式。

#include <iostream>
#include <vector>
using namespace std;

int main (){
   vector<int> myvector1 {123,234,345};
   vector<int> myvector2 {123,234,345};
   if (myvector1 <= myvector2)
      cout<<"myvector1 is less than or equal to myvector2.\n";
   else
      cout<<"myvector1 is not less than or equal to myvector2.\n";
   return 0;
}

輸出

當我們編譯並執行上述程式時,將產生以下結果:

myvector1 is less than or equal to myvector2.

示例 2

考慮另一種情況,我們將獲取字串值並進行比較。

#include <iostream>
#include <vector>
using namespace std;

int main (){
   vector<string> myvector1 {"abc","bcd","cde"};
   vector<string> myvector2 {"abc","bcd"};
   if (myvector1 <= myvector2)
      cout<<"myvector1 is less than or equal to myvector2.\n";
   else
      cout<<"myvector1 is not less than or equal to myvector2.\n";
   return 0;
}

輸出

執行上述程式後,將產生以下結果:

myvector1 is not less than or equal to myvector2.

示例 3

在以下示例中,我們將使用 push_back() 函式插入值並應用 operator<=() 函式。

#include <vector>
#include <iostream>

int main( ){ 
   using namespace std;
   vector <int> myvector1, myvector2;
   myvector1.push_back( 1 );
   myvector1.push_back( 2 );
   myvector1.push_back( 4 );
   myvector2.push_back( 1 );
   myvector2.push_back( 23 );
   if ( myvector1 <= myvector2 )
      cout << "myvector1 is less than or equal to vector myvector2." << endl;
   else
      cout << "myvector1 is greater than vector myvector2." << endl;
}

輸出

執行上述程式後,將產生以下結果:

myvector1 is less than or equal to vector myvector2.
廣告

© . All rights reserved.