Re: how to have user defined hash for unordered_map ?
On 2008-07-11 01:05:57 -0400, abir <abirbasak@gmail.com> said:
Hi,
I want a user defined key for tr1 unordered_map.
My classes are,
template<typename T>
struct work{
int count;
work(int count) : count(count){}
};
template<typename W>
class worker{
public:
typedef worker<W> self_type;
worker(W& w,int pos) : w_(&w),pos_(pos){}
bool operator== (const self_type& other) const {
assert(w_ == other.w_);
return pos_ == other.pos_;
}
private:
W* w_;
int pos_;
friend std::size_t hash(const self_type& self){
return self.pos_ + w_->count;
}
};
and want to have worker class as key to map.
so calling is,
typedef work<int> WORK;
typedef worker<WORK> WORKER;
WORK w(2);
WORKER w1(w,1);
WORKER w2(w,2);
WORKER w3(w,3);
unordered_map<WORKER,int> m;
m.insert(std::make_pair(w1,5));
i have == op for worker.and either declaring a hash_value or hash
function is not working.
how can i do it?
unordered_map takes five template arguments, three of which have defaults:
template <class Key, class T,
class Hash = hash<Key>, class Pred = std::equal_to<Key>,
class Alloc = std::allocator<std::pair<const Key, T>>>
class unordered_map;
To provide your own hash object, use its type as the third argument. To
provide your own equality predicate, use its type as the fourth
argument. To provide your own allocator, use its type as the fifth
argument.
With just those changes, you'll get default-constructed versions of
your hash type, equality type, and allocator type. If that's not
appropriate, unordered_map has constructors that take objects of those
types.
--
Pete
Roundhouse Consulting, Ltd. (www.versatilecoding.com) Author of "The
Standard C++ Library Extensions: a Tutorial and Reference
(www.petebecker.com/tr1book)