Let’s say I have a Rectangle class like so:
class Rectangle {
public:
double width;
double height;
}
Now I wish to store two possibly different lists of Rectangles as heaps, except that the first heap should be based on width and the second on height. Also, I wish to use the stl’s make_heap function to heapify. Ideally, I should be able to call .heapify() on a heap, and based on the class that it belongs to, the heap in question should heapify itself by passing the correct comparison function to make_heap, perhaps using dynamic dispatch. What I have is the following:
class Heap {
public:
vector<Rectangle> data;
virtual bool comp(Rectangle a, Rectangle b);
void heapify() { make_heap(data.begin(), data.end(), comp); }
// other methods that make use of comp directly
}
class WidthHeap : public Heap {
bool comp(Rectangle a, Rectangle b); // compares by width
}
class HeightHeap : public Heap {
bool comp(Rectangle a, Rectangle b); // compares by height
}
This is all wrong because I guess I just don’t understand functions in C++, which is why I would like your help.
Because
compis a member function pointer, it cannot be called without passingthis. You need to bindthisto it:std::bindcan be found in the<functional>header in C++11, and also available asstd::tr1::bindin<tr1/functional>using TR1. If you can’t use TR1 or C++11, there’s a Boost library for it.Demo: http://ideone.com/5zhmg