【问题标题】:C++ STL Containers. Parametrize a comparer for each different instanceC++ STL 容器。为每个不同的实例参数化一个比较器
【发布时间】:2013-04-16 16:29:56
【问题描述】:

我有一组表示地图坐标的 n 个对象,我希望每个对象都使用 k 维护一个 priority_queue em> 最接近他们的位置。

问题是 priority_queue 接收谓词类而不是函数对象,所以我还没有找到一种方法来为每个 指定不同的参考点 >priority_queue

例如:

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

相对于:

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

from 设为静态确实无济于事,因为我需要为每个 priority_queue

使用不同的 point reference

【问题讨论】:

    标签: c++ stl priority-queue predicate


    【解决方案1】:

    std::priority_queue 具有构造函数重载,采用比较器类的 istance。因此,您只需将比较器设计为有状态的(您似乎已经这样做了),并相应地构造优先级队列:

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

    【讨论】:

    • 这很容易。我想我可以搜索得更好。谢谢!!
    【解决方案2】:

    您需要将类作为模板参数传递,并将类的对象作为参数传递给构造函数,因此:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-09-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-01-03
      • 2020-02-20
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多