C++ initialize priority_queue with custom compare function
<p>I have a <code>Dijkstra</code> class which uses a <code>priority_queue</code> with a custom compare function. I named the queue <code>DijkstraPriorityQueue</code> with a <code>using</code> statement. Inside the class constructor, I initialize the queue. To do that, I give the compare function in a lambda expression. </p>

<p>For the first queue, <code>PQ1</code>, the compare function is <code>{ return distTo[u] &gt; distTo[v]; }</code> and this compiles fine, because the <code>vector&lt;float&gt; distTo</code> is a member of the class.</p>

<p>But for the second queue, <code>PQ2</code>, the function is <code>{ return distTo2[u] &gt; distTo2[v]; }</code> where <code>vector&lt;float&gt; distTo2</code> is just a temporary variable inside the constructor, and that doesn't compile. (I think that's the reason at least)</p>

<p>Also, I randomly tried to change <code>vector&lt;float&gt; distTo2</code> to <code>static vector&lt;float&gt; distTo2</code> by intuition and it compiles, however I don't think this is what I want to be doing. I am not familiar with static variables inside functions, since that doesn't exist in Java or C#. At any case, what is a clean solution to make the code below compile and work as intended ?</p>

<p><strong>Dijkstra.h</strong></p>

<pre><code>class Dijkstra
{
public:
    Dijkstra();  
    ~Dijkstra();       

private:    
    vector&lt;float&gt; distTo;
};
</code></pre>

<p><strong>Dijkstra.cpp</strong></p>

<pre><code>using DijkstraPriorityQueue = priority_queue&lt;int, vector&lt;int&gt;, function&lt;bool(int, int)&gt;&gt;;

Dijkstra::Dijkstra()
{           
    distTo = vector&lt;float&gt;(V, FLT_MAX);
    // Compiles fine
    DijkstraPriorityQueue PQ1 = DijkstraPriorityQueue([this](int u, int v)
        { return distTo[u] &gt; distTo[v]; });

    vector&lt;float&gt; distTo2 = vector&lt;float&gt;(V, FLT_MAX);
    // Doesn't compile
    DijkstraPriorityQueue PQ2 = DijkstraPriorityQueue([this](int u, int v)
        { return distTo2[u] &gt; distTo2[v]; });
}
</code></pre>

<p><strong>Edit:</strong> </p>

<p>The following code compiles too. Any clues why ? Can someone explain what <strong>capture</strong> is on lambda expressions ? Or how should I write my code properly in this specific case ?</p>

<pre><code>DijkstraPriorityQueue PQ2 = DijkstraPriorityQueue([distTo2](int u, int v)
    { return distTo2[u] &gt; distTo2[v]; });
</code></pre>