问题
Hi I wonder if I can set up another linked struct myself to actually set up my own order between keys in the unordered_map? or there is a standard library? I need the fast look up function of unordered_map...
For example:
#include<string>
#include<tr1/unordered_map>
struct linker
{
string *pt;
string *child1;
string *child2;
};
unordered_map<string,int> map({{"aaa",1},{"bbb",2},{"ccc",3},{"ddd",4}});
linker node1 = new linker;
node1.pt = &map.find("aaa")->first;
node1.child1 = &map.find("ccc")->first;
node1.child2 = &map.find("ddd")->first;
回答1:
One way to optimize hash lookup is to find a hash function that produces the smallest number of hash collisions on the keys you are going to use.
With std::unordered_map
you can also get local iterators to buckets and rearrange the elements in the bucket, if you are so inclined.
回答2:
A far better solution IMHO would be as follows:
struct comparator {
bool operator()(string const& lhs, string const& rhs) {
return ...;//Your definition of order here!!!
}
};
std::map<string, int, comparator> map{{"aaa",1},{"bbb",2},{"ccc",3},{"ddd",4}};//note the elided paranthesis
Now you can simply use the iterator pair begin()/end() of this map which will be in a specified order see in the accepted answer to this question
来源:https://stackoverflow.com/questions/17223708/hybrid-linked-list-constructed-on-unordered-map