hybrid linked list constructed on unordered_map?

有些话、适合烂在心里 提交于 2019-12-24 03:16:28

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!