I am new to C++, and I know that unordered_map uses hashing and map uses red black tree. I am confused why hashing is required for unordered_map whereas not in map. What is the reason?
#include <bits/stdc++.h>
using namespace std;
struct hash_pair {
template <class T1, class T2>
size_t operator()(const pair<T1, T2>& p) const
{
auto hash1 = hash<T1>{}(p.first);
auto hash2 = hash<T2>{}(p.second);
return hash1 ^ hash2;
}
};
int main()
{
unordered_map<pair<int, int>, int, hash_pair> hmap1;
hmap1[{1,1}]=2;
if (hmap1.find({1,1})!=hmap1.end()) cout<<"Value found :"<<hmap1[{1,1}]<<endl;
if (hmap1.find({0,0})==hmap1.end()) cout<<"Value not found"<<endl;
map<pair<int, int>, int> hmap2;
hmap2[{2,2}]=4;
if (hmap2.find({2,2})!=hmap2.end()) cout<<"Value found :"<<hmap2[{2,2}]<<endl;
if (hmap2.find({0,0})==hmap2.end()) cout<<"Value not found"<<endl;
return 0;
}
Output:
Value found :2
Value not found
Value found :4
Value not found