I have a Nx by Ny vector of objects A.
Ahas membersaandb.- If member
bmeets a certain criteria, it is added to a vector of pointersheapItem. - I then want to use the function
std::make_heapto create a minimum heap.
Then, in my code, I want to change the value of A[i][j].b present in the heap and want the heap to reflect these changes.
For this, I would need to write a filterUp and filterDown routine. My problem is that I do not know the location of the A[i][j].b in the heap. Is there any way I can find out or another way to write the trickleUp & trickleDown routines? I don’t want to constantly call the make_heap function for it might be costly.
#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;
}
You have a heap of A* pointers. You need the index of an A* obj in the heap in order to preserve heap structure after manipulating obj. There is no way to get it other than searching the entire heap. Here are some options: