我有一个对象向量Nx
。Ny
A
A
有成员a
和b
.- 如果成员
b
满足特定条件,则将其添加到指针向量中heapItem
。 - 然后我想使用该函数
std::make_heap
来创建一个最小堆。
然后,在我的代码中,我想更改A[i][j].b
堆中存在的值,并希望堆反映这些更改。
为此,我需要编写一个filterUp
和filterDown
例程。我的问题是我不知道A[i][j].b
堆中的位置。有什么方法可以找到或另一种方法来编写trickleUp
&trickleDown
例程?我不想经常调用该make_heap
函数,因为它可能代价高昂。
#include <vector>
#include <iostream>
#include <algorithm>
#include <cmath>
struct A
{
A(){}
A(int av, int bv):a(av),b(bv){}
int a, b;
};
struct MinHeap
{
bool operator()(const A* lhs, const A* rhs) const
{
return lhs->b > rhs->b;
}
};
int main()
{
int Nx=4;
int Ny=3;
int cnt=0;
std::vector<A*> heapItem;
A gridPt[Nx][Ny];
for(int i=0; i<Nx; ++i) // initialize grid of A objects
{
for(int j=0; j<Ny; ++j)
{
gridPt[i][j].a=i*(-j)+2*j+i+j;
gridPt[i][j].b=i+j*(-2)+4;
if(gridPt[i][j].b>0) // add selected A objects to heap
{
heapItem.push_back(&gridPt[i][j]);
cnt++;
}
}
}
std::make_heap(heapItem.begin(), heapItem.end(), MinHeap()); //make heap
gridPt[1][2].b=3; //this object is in heap. need to call a filterUp or filterDown routine to retain min heap structure
int count=0;
for(int i=0; count<heapItem.size(); ++i)
{
for(int j=0; j<pow(i,2) && count<heapItem.size(); ++j)
{
std::cout << heapItem[count++]->b << " ";
}
std::cout << std::endl;
}
//make_heap, push_heap, pop_heap maintain min heap structure
return 0;
}