Reputation: 2190
I'm using unordered_map<> and am curious, when specifying a hash function as the second argument (per code below) a size_type n
bucket count must be specified as the first argument in the constructor. I have read the default bucket count should be used. Does anyone know how to use the default bucket count parameter when using your own hash function?
Interestingly, Stroustrup C++ 4th Ed Page 918 constructs an unordered_set<> without use of bucket size and does not agree with the documented constructor arguments.
explicit unordered_map ( size_type n = /* see below */,
const hasher& hf = hasher(),
const key_equal& eql = key_equal(),
const allocator_type& alloc = allocator_type() );
Example usage:
#include <unordered_map>
#include <functional>
#include <iostream>
using namespace std;
struct X {
X(string n) : name{n} {}
string name;
bool operator==(const X& b0) const { return name == b0.name; }
};
namespace std {
template<>
struct hash<X> {
size_t operator()(const X&) const;
};
size_t hash<X>::operator()(const X& a) const
{
cout << a.name << endl;
return hash<string>{}(a.name);
}
}
size_t hashX(const X& a)
{
return hash<string>{}(a.name);
}
int main()
{
// unordered_map<X,int,hash<X>> m(100, hash<X>{});
// unordered_map<X,int,function<size_t(const X&)>> m(100, &hashX);
unordered_map<X,int,size_t(*)(const X&)> m(100, &hashX);
X x{"abc"};
m[x] = 1;
int i = m[x];
cout << i << endl;
}
Upvotes: 7
Views: 1361
Reputation: 7249
It seems like we can access the bucket_count
value. I would just run the following code in your environment and check what values it gives you.
#include <iostream>
#include <unordered_map>
int main() {
std::unordered_map<int, int> m;
std::cout << m.bucket_count() << std::endl;
return 0;
}
This outputs 1
in ideone
Upvotes: 4