c++11 - How to correctly use an unordered_map C++ -
i wanted create std::unordered_map custom hash function. having trouble figuring out declare/how use unordered_map though.
here situation. have class called object. it's super simple , merely contains integer id. here header file:
// object.hpp class object { public: object(); ~object(){}; int id(); void setid(int i); private: int id; }; i have class called dataset acts container hold millions of these objects. simplicities sake, want able construct dataset, add object dataset, delete object id dataset, clear dataset, , size of dataset.
the structure want (and required to) use in dataset class std::unordered_map. map, want key integer id associated object, , actual object* value. have hash function want use unordered_map. here have in dataset header file:
// dataset.hpp struct hashkey { unsigned int hash(unsigned int x) { x = ((x >> 16) ^ x) * 0x45d9f3b; x = ((x >> 16) ^ x) * 0x45d9f3b; x = ((x >> 16) ^ x); return x; } }; class dataset{ public: std::unordered_map<int,object*,hashkey> objects; dataset(); ~dataset(); int addobject(object *object); void clear(); int deleteobject(int id); int getsize(); }; as of right i'm trying figure out how create addobject in dataset.cpp. here (broken) try:
int dataset::addobject(object *object) { objects.emplace(object->id(),object); return 1; } when compiled, end error:
type 'const hashkey' not provide call operator {return static_cast<const _hash&>(*this)(__x.__cc.first);} what want able in file called driver.cpp, have loop add millions of objects. this:
dataset container; for(int = 0; < 10000000; ++i) { object *object = new object(); object->setid(i); container.addobject(object); } is there way make unordered_map can accomplish this? side note, required use current dataset class , current object class is. need make std::unordered_map it.
you need define hash function const call operator (i.e. operator()) takes object of key type , returns size_t:
size_t operator()(int x) const { ... }
Comments
Post a Comment