Matthew Hoggan
Matthew Hoggan

Reputation: 7594

make_heap using function object

What operator do I have to overload for make_heap? Is it the () operator? If I already have that defined for another case in my algorithm. Can anyone provide the correct way to use make_heap in my case. Please see code below to better understand.

Inside a vertex class I have

bool operator() (vertex &v) const 
{ 
  return (v.key() == _key); 
}

This is used while constructing a graph in the following std method find_if

vertex_iterator GraphComponents::graph::find_vertex_by_key(int key)
{
  return std::find_if(_vertices.begin(), _vertices.end(), GraphComponents::vertex(key));
}

Now in my algorithm I want to use vertex as a Function object under a different context.

std::list<int> GraphComponents::graph::breadth_first_search (int key, int start_key)
{
  std::vector<GraphComponents::vertex *> heap;
  for (vertex_iterator copy_iter = _vertices.begin(); copy_iter != _vertices.end(); ++copy_iter) {
    heap.push_back(&(*copy_iter));
  }
  std::make_heap(heap.begin(), heap.end(), vertex(<should be distance>));
}

Here I don't want to use the key in the comparison, but I want to use a distance member so the vertex that has the shortest distance is at the top of the heap. Short from implementing my own heap what is the recommended way around this?

Upvotes: 0

Views: 1343

Answers (1)

Benjamin Lindley
Benjamin Lindley

Reputation: 103693

Implement a function which takes two arguments of your type, and returns true if the left hand argument should be considered relatively less than the right hand argument. (less can mean greater)

Then pass that function as the third argument to make_heap. Or you can implement operator< using the semantics described above, and that will be used if you don't pass any function.

http://en.wikipedia.org/wiki/Strict_weak_ordering

In your case, your elements are pointers, so you can't write an operator<, as that function is already defined for all pointer types. So you will have to write a separate function, something like this:

bool CompareByDistance(const GraphComponents::vertex * lhs,
                       const GraphComponents::vertex * rhs)
{
    return lhs->distance() < rhs->distance();
}

Upvotes: 5

Related Questions