简体   繁体   English

C ++ STL容器。 为每个不同的实例参数化一个比较器

[英]C++ STL Containers. Parametrize a comparer for each different instance

I have a set of n objects representing coordinates in a map, and I want for each one of them to mantain a priority_queue with the k closest to their position. 我有一组代表地图中坐标的n个对象,并且我希望每个对象都保留一个k距离其位置最近的priority_queue

Problem is priority_queue receives a class for a predicate instead of a function object so I haven't found a way to specify a diferent point of reference for every priority_queue 问题是priority_queue接收到一个谓词类而不是函数对象,因此我还没有找到一种为每个priority_queue指定不同参考点的方法

ie something like: 即类似:

std::priority_queue<
  Vertex*, 
  std::vector<Vertex*>, 
  DistanceComparer(fromVertex)> 
  pqueue; // doesn't compile

as opposed to: 相对于:

DistanceComparer::from = fromVertex;
std::priority_queue<
  TRVertex*, 
  std::vector<TRVertex*>, 
  DistanceComparer> 
  pqueue; // compiles but unhelpful

Making from static really doesn't help since I need a different point reference for every priority_queue 使用静态方法确实无济于事,因为我需要为每个priority_queue使用不同的点引用

You need to pass the class as the template parameter, and an object of the class as an argument to the constructor, thusly: 您需要将类作为模板参数传递,并将类的对象作为构造函数的参数传递,因此:

std::priority_queue<
    TRVertex*, 
    std::vector<TRVertex*>, 
    DistanceComparer> 
  pqueue(DistanceComparer(fromVertex));

std::priority_queue has constructor overloads taking an istance of the comparator class. std::priority_queue具有构造函数重载,采用比较器类的形式。 So you just have to design your comparator as stateful (which you seem to have done already), and construct the priority queue accordingly: 因此,您只需将比较器设计为有状态的(您似乎已经完成),并相应地构造优先级队列:

struct Vertex
{
  std::priority_queue<Vertex*, std::vector<Vertex*>, DistanceComparer> pqueue;
  explicit Vertex(fromVertex *v) : pqueue(v) {}
};

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

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