简体   繁体   中英

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.

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

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

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. 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) {}
};

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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