【发布时间】:2016-11-28 18:23:59
【问题描述】:
我正在尝试实现一个数据结构,它是堆和无序映射的组合。 堆将保存图形节点,包含标识符和成本。 我使用 min_extract 函数让节点在 log(n) 时间内展开。 [我正在使用算法中的 std::vector 和 std::make_heap 、 pop_heap 等实现堆]
无序映射将节点 , 位置保存在向量映射中。无序映射用于支持包含和更新节点功能。但是对于我来说,我需要节点与其在向量中的位置之间的映射,否则我不得不对项目进行线性搜索。
更令人担忧的是,我推送或弹出一个项目,并调用 push_heap 或 pop_heap,这将围绕向量中的节点移动,而我在地图中维护的位置最终会出错。
那么我该如何实现该功能,我可以在其中维护节点与其位置之间的映射。
void push(T elem) // This will 0(n)... As the element has to be found
{
heapVec_.push_back(elem); // add tp vec
std::push_heap<compar_> (heapVec_.begin() , heapVec_.end());
// sort ? or just find in the vec ?
std::size_t pos = 0 ;
// find position of the item in the vector
std::find_if(heapVec_.begin() , heapVec_.end() , [&pos , &elem](const T& item)
{
if(item == elem)
{
return true;
}
else
{
++pos;
}
});
// add to map
heapMap_.emplace_back(elem , pos); // how to keep track of the element where this object is added to ?
}
我正在寻找的数据结构必须支持: 找到最小值:O(lg n) 包含:O(1) 更新节点:O(lg n) 插入:O(lg n)
如果我推出自己的堆,当我向上或向下做气泡时,我会更新地图中节点的位置,这将是微不足道的。在我这样做之前,我想确保我不能在 STL 中做到这一点。
【问题讨论】:
标签: c++ algorithm vector stl unordered-map