简体   繁体   English

make_heap使用函数对象

[英]make_heap using function object

What operator do I have to overload for make_heap? 我必须为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. 在我的情况下,谁能提供使用make_heap的正确方法。 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 在以下std方法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. 现在,在我的算法中,我想在不同的上下文中将顶点用作Function对象。

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? 除了实现自己的堆之外,推荐的解决方法是什么?

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. 实现一个函数,该函数接受您类型的两个参数,如果应将左手参数视为相对小于右手参数,则返回true。 (less can mean greater) (越少意味着越大)

Then pass that function as the third argument to make_heap . 然后将该函数作为第三个参数传递给make_heap Or you can implement operator< using the semantics described above, and that will be used if you don't pass any function. 或者,您可以使用上述语义来实现operator< ,如果您不传递任何函数,则将使用该语义。

http://en.wikipedia.org/wiki/Strict_weak_ordering 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. 在您的情况下,您的元素是指针,因此您无法编写operator< ,因为该函数已为所有指针类型定义。 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();
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM