C++ unordered_map::operator== 函式



C++ 的std::unordered_map::operator== 函式用於檢查兩個無序對映是否相等。如果兩個無序對映相等,則返回 true,否則返回 false。

如果我們比較資料型別不同的無序對映,則 unordered_map::operator== 函式將顯示錯誤。它僅適用於具有相同資料型別的無序對映。

語法

以下是 std::unordered_map::operator== 函式的語法。

bool operator==(const unordered_map<Key,T,Hash,Pred,Alloc>& first,
                const unordered_map<Key,T,Hash,Pred,Alloc>& second
               );

引數

  • first - 第一個無序對映物件。
  • second - 第二個無序對映物件。

返回值

如果兩個無序對映相等,則此函式返回 true,否則返回 false。

示例 1

在以下示例中,讓我們看看 operator== 函式的用法。

#include <iostream>
#include <unordered_map>
using namespace std;
int main(void) {
   unordered_map<char, int> um1;
   unordered_map<char, int> um2;
   if (um1 == um2)
      cout << "Both unordered_maps are equal" << endl;
   um1.emplace('a', 1);
   if (!(um1 == um2))
      cout << "Both unordered_maps are not equal" << endl;
   return 0;
}

輸出

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

Both unordered_maps are equal
Both unordered_maps are not equal

示例 2

讓我們看下面的例子,我們將應用 operator== 函式來檢查儲存相同元素但順序不同的無序對映是否相等。

#include <iostream>
#include <unordered_map>
using namespace std;
int main(void) {
   unordered_map<char, int> um1 = {{'C', 3}, {'B', 2}, {'A', 1}, {'D', 4}};
   unordered_map<char, int> um2 = {{'D', 4}, {'A', 1}, {'B', 2}, {'C', 3}};
   if (um1 == um2)
      cout << "Both unordered_maps are equal" << endl;
   return 0;
}

輸出

以下是以上程式碼的輸出:

Both unordered_maps are equal

示例 3

考慮另一種情況,我們將應用 operator== 函式來檢查儲存不同元素但資料型別相同的無序對映是否相等。

#include <iostream>
#include <unordered_map>
using namespace std;
int main(void) {
   unordered_map<char, int> um1 = {{'E', 5}, {'f', 6}, {'g', 7}, {'H', 8}};
   unordered_map<char, int> um2 = {{'D', 4}, {'A', 1}, {'B', 2}, {'C', 3}};
   if (um1 == um2)
      cout << "Both unordered_maps are equal" << endl;
   if (!(um1 == um2))
      cout << "Both unordered_maps are not equal" << endl;
   return 0;
}

輸出

以上程式碼的輸出如下:

Both unordered_maps are not equal
廣告