This is weird.. the following code (which I managed to compile thanks to Cassio Neri) is compiling without any error.. by the way either hashing_func nor key_equal_func do get called (the couts aren't showing in the console window)
#include <iostream>
#include <string>
#include <unordered_map>
#include <algorithm>
#include <functional>
using namespace std;
unsigned long hashing_func(string key)
{
cout << "Hashing called";
unsigned long hash = 0;
for(int i=0; i<key.size(); i++)
{
hash += (71*hash + key[i]) % 5;
}
return hash;
}
template<class T> bool key_equal_fn(T t1, T t2)
{
return t1 == t2;
}
template <> bool key_equal_fn<string>(string t1, string t2)
{
cout << "Equal called";
return !(t1.compare(t2));
}
int main ()
{
unordered_map<string, string>::size_type n = 5;
unordered_map<string, string> mymap(n, (const std::hash<string> &)hashing_func,
(const std::equal_to<string> &)(function<bool(string,string)>(key_equal_fn<string>))) ;
bool case_insensitive = mymap.key_eq()("test","TEST");
mymap["paul"] = "jenna";
mymap["frank"] = "ashley";
if(mymap["paul"] == mymap["frank"])
cout << "equal" << endl;
return 0;
}
I'm using MSVC2012, any hint on what could be the problem?
The unordered_map::hash_function() is a built in function in C++ STL which is used to get the hash function. This hash function is a unary function which takes a single argument only and returns a unique value of type size_t based on it.
Insertion of spread keys in std::map tends to outperform std::unordered_map when map size is under 10000 elements. Insertion of dense keys in std::map doesn't present performance difference with std::unordered_map under 1000 elements. In all other situations std::unordered_map tends to perform faster.
Note: unordered_map container performs faster than map when they have to access an individual element by their key.
The comparison between unordered_map objects is not affected by the arbitrary order in which they store their elements. Two unordered_maps are equal if they have the same number of elements and the elements in one container are a permutation of the elements in the other container. Otherwise, they are unequal.
You have to specify hash/compare functions with template arguments, not in the constructor. Here is an example:
class Hasher
{
public:
size_t operator() (string const& key) const
{
cout << "Hashing called";
size_t hash = 0;
for(size_t i=0; i<key.size(); i++)
{
hash += (71*hash + key[i]) % 5;
}
return hash;
}
};
class EqualFn
{
public:
bool operator() (string const& t1, string const& t2) const
{
cout << "Equal called";
return !(t1.compare(t2));
}
};
unordered_map<string, string, Hasher, EqualFn> mymap(5);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With