用优先级队列分离链接(使用std::map)

Separate chaining with priority queue (using std::map)

本文关键字:std map 使用 优先级 队列 分离 链接      更新时间:2023-10-16

我刚开始学习哈希表,而尝试与std::map我提出了这个问题:当使用单独的链接方法来解决碰撞,我可以使用std:: priority_queue而不是仅仅列表?

例如,有一大群人,我有他们的名字和年龄的信息,我想要得到的是具有相同名字的人的排序列表。

因此,为了做到这一点,我首先使用他们的名字作为将这些人放入地图的键,然后使用std::priority_queue基于年龄解决导致冲突的具有相同名字的人。

这是解决这个问题的正确方法吗?我只是意识到我真的不知道std::map背后的秘密,它是使用分离链还是线性探测来解决碰撞?我找不到答案。

对于我所描述的问题,我有一个简单的代码,可能有助于澄清一点:

class people {
public:
people(string inName, int inAge):firstName(inName), age(inAge){};
private:
string firstName;
int age;

}
int main(int argc, char ** argv) {
string name;
int age;
name = "David";
age = 25;
people  aPerson(name, age);
//This is just an example, there are usually more than two attributes to deal with.

std::map <string, people> peopleList;
peopleList[name] = aPerson;
//now how do I implement the priority queue for collision first names? 
}

提前感谢!

编辑:因为我需要O(1)搜索,我应该使用无序映射而不是映射。

现在您有一个名称和单个people对象之间的映射。您需要将映射更改为名称和std::priority_queue之间的映射,并为优先级队列使用自定义比较器:

auto comparator = [](const people& p1, const people& p2) -> bool
    { return (p1.age < p2.age); }
std::map<std::string,
         std::priority_queue<people, std::vector<people>, comparator>> peopleList;
// ...
peopleList[name].push(aPerson);