访问类

时间:2016-02-27 08:50:57

标签: c++ c++11 stl

如果您查看下面的代码,我正在尝试创建一个priority_queue,我将其命名为DijkstraPriorityQueue,它有一个自定义比较器,它也使用私有向量distTo

你可以看到我有一些点.......,因为我尝试过的一切都失败了。

在这种特定情况下,如何使其按预期工作,最简洁的解决方案(或可能的解决方案)是什么?

Dijkstra.h

class Dijkstra
{
public:
    Dijkstra(Graph G, int s);                          // Create
    ~Dijkstra();                                       // Destroy

private:
    bool compare(int u, int v)
    {
        return distTo[u] < distTo[v];
    }
    typedef priority_queue<int, vector<int>, .........> DijkstraPriorityQueue;


    vector<float>         distTo; // distTo[u] is the distance of the shortest s->u path 
    DijkstraPriorityQueue PQ;     // Min-Priority Queue, implemented for Dijkstra
};

Dijkstra.cpp

Dijkstra::Dijkstra(Graph G, int s)
{
     PQ = DijkstraPriorityQueue(...........);
}

1 个答案:

答案 0 :(得分:2)

选项#1

#include <functional>
#include <queue>
#include <vector>

class Dijkstra
{
public:
    Dijkstra()
        : PQ([this](int u, int v){ return distTo[u] < distTo[v]; })
    {
    }

private:    
    using DijkstraPriorityQueue
       = std::priority_queue<int, std::vector<int>, std::function<bool(int,int)>>;

    std::vector<float> distTo;

    DijkstraPriorityQueue PQ;
};

选项#2

#include <functional>
#include <queue>
#include <vector>

class Dijkstra
{
public:
    Dijkstra()
        : PQ(std::bind(&Dijkstra::compare, this, std::placeholders::_1, std::placeholders::_2))
//      or
//      : PQ([this](int u, int v){ return compare(u, v); })
    {
    } 

private:    
    bool compare(int u, int v) const
    {
        return distTo[u] < distTo[v];
    }

    using DijkstraPriorityQueue
       = std::priority_queue<int, std::vector<int>, std::function<bool(int,int)>>;

    std::vector<float> distTo;

    DijkstraPriorityQueue PQ;
};

选项#3

(对于记录,如果您遇到C ++ 03):

#include <queue>
#include <vector>

class Dijkstra
{
public:
    Dijkstra()
        : PQ(compare(this))
    {
    }

private:
    struct compare
    {
        explicit compare(Dijkstra* d) : d(d) {}

        bool operator()(int u, int v) const
        {
            return d->distTo[u] < d->distTo[v];
        }

        const Dijkstra* d;
    };

    typedef std::priority_queue<int, std::vector<int>, compare> DijkstraPriorityQueue;

    std::vector<float> distTo;

    DijkstraPriorityQueue PQ;
};