用优先级队列分离链接(使用std::map)
Separate chaining with priority queue (using std::map)
我刚开始学习哈希表,而尝试与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);
相关文章:
- 如何导出包含具有"std::unique_ptr"值的"std::map"属性的
- 使用一个考虑到std::map中键值的滚动或换行的键
- 有没有办法对std::unordered_set、std::unrdered_map、std::set、std::map
- 将重物插入std::map
- 使用通用值初始化 std::map,不重复
- 仅包含可移动 std::map 的类的移动构造函数不起作用
- C++:当所有条目都保证是唯一时,替代 std::map
- 使用模板化的键类型定义 std::map,该键类型基于作为参数接收的函数
- 如果 KEY 是 std::list 或 std::vector 而不是值,那么 std::map 的默认行为是什么?
- C++如何创建 std::map
- 从其他容器中移动构造"std::map"
- 将 std::map::emplace 与返回 shared_ptr 的函数一起使用是否正确?
- C++中 std::map 的运行时复杂度是多少?
- 为什么在 std::map 上移动无法将元素从一个映射移动到另一个映射
- 使用重载 [] 运算符返回 std::map() 的可赋值
- std::map, std::unordered_map - 缩小初始值设定项列表中的转换范围
- C++ 使用枚举类对象分配 std::map 值
- 静态 std::map instatiation 在类的方法中调用构造函数吗?
- std::map:当元素不可默认构造时创建/替换元素
- Arduino编译器和STL:使用std::vector和std::map