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



C++ vector::operator!=() 函式用於測試兩個向量是否不相等,如果給定的兩個向量不相等,則返回 true,否則返回 false。Operator !=() 函式首先檢查兩個容器的大小,如果大小相同,則按順序比較元素,並在第一次不匹配時停止比較。此成員函式永遠不會丟擲異常,並且 operator!=() 函式的時間複雜度為線性。

語法

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

template <class T, class Alloc>
bool operator!= (const vector<T,Alloc>& lhs, const vector<T,Alloc>& rhs); 

引數

  • lhs - 表示第一個向量
  • rhs - 表示第二個向量

示例 1

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

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

int main(void) {
   vector<int> v1;
   vector<int> v2;
   v1.resize(10, 100);
   if (v1 != v2)
      cout << "v1 and v2 are not equal" << endl;
   v1 = v2;
   if (!(v1 != v2))
      cout << "v1 and v2 are equal" << endl;
   return 0;
}

輸出

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

v1 and v2 are not equal
v1 and v2 are equal

示例 2

考慮另一種情況,我們將採用字串值並應用 operator!=() 函式。

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

int main (){
   vector<string> myvector1 {"RS7","AUDI","MAYBACH GLS"};
   vector<string> myvector2 {"RS7","AUDI","MAYBACH GLS"};
   if (myvector1 != myvector2)
      cout<<"The Two Vectors are not equal.\n";
   else
      cout<<"The Two Vectors are equal.\n";
   return 0;
}

輸出

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

The Two Vectors are equal.

示例 3

在以下示例中,我們將使用 push_back() 函式插入值,並檢查向量是否相等。

#include <vector>
#include <iostream>

int main( ){
   using namespace std;
   vector <int> myvector1, myvector2;
   myvector1.push_back( 11 );
   myvector1.push_back( 113 );
   myvector2.push_back( 222 );
   myvector2.push_back( 113 );
   if ( myvector1 != myvector2 )
      cout << "Vectors are not equal." << endl;
   else
      cout << "Vectors are equal." << endl;
}

輸出

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

Vectors are not equal.
廣告