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 - 第二个无序映射对象。

Explore our latest online courses and learn new skills at your own pace. Enroll and become a certified expert to boost your career.

返回值

如果两个无序映射相等,则此函数返回 true,否则返回 false。

示例 1

在以下示例中,让我们看看 operator== 函数的用法。

Open Compiler
#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== 函数来检查存储相同元素但顺序不同的无序映射是否相等。

Open Compiler
#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== 函数来检查存储不同元素但数据类型相同的无序映射是否相等。

Open Compiler
#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
广告