title: Comparator function in Priority Queue
body: <p>I'm trying to understand how the comparator function return value determines which element goes before the other when inserting into a Priority Queue.</p>
  <p>Below code stores integers in the descending order based on a comparator function.
  I understand that I do not need a comparator function for this simple evaluation, but its easier to visualize with simple data.</p>
  <pre><code>#include &lt;iostream&gt;
  #include &lt;vector&gt;
  #include &lt;queue&gt;
  
  using namespace std;
  
  struct Compfunc {
      bool operator() (const int &amp;a, const int &amp;b) {
          //cout &lt;&lt; &quot;a: &quot; &lt;&lt; a &lt;&lt; &quot; vs b: &quot; &lt;&lt; b &lt;&lt; endl;
          return (a &lt; b);
      }
  };
  
  void callPQ(vector&lt;int&gt; &amp;vec) {
      priority_queue&lt;int, vector&lt;int&gt;, Compfunc&gt; pq;
      
      for (auto num : vec) {
          cout &lt;&lt; &quot;Pushing : &quot; &lt;&lt; num &lt;&lt; endl;
          pq.push(num);
      }
  
      cout &lt;&lt; &quot;Printing:&quot; &lt;&lt; endl;
      while (!pq.empty()) {
          cout &lt;&lt; pq.top() &lt;&lt; endl;
          pq.pop();
      }
  }
  
  int main()
  {
      vector&lt;int&gt; vec{5, 6, 4, 9, 2, 0};
      
      callPQ(vec);
      return 0;
  }
  </code></pre>
  <p>Output,</p>
  <pre><code>Pushing : 5
  Pushing : 6
  Pushing : 4
  Pushing : 9
  Pushing : 2
  Pushing : 0
  Printing:
  9
  6
  5
  4
  2
  0
  </code></pre>
  <p>From <a href="http://www.cplusplus.com/reference/queue/priority_queue/" rel="nofollow noreferrer">http://www.cplusplus.com/reference/queue/priority_queue/</a></p>
  <blockquote>
  <p>The expression comp(a,b), where comp is an object of this type and a and b are elements in the container, shall return true if a is considered to go before b in the strict weak ordering the function defines.</p>
  </blockquote>
  <p>Is the following observation correct?</p>
  <ol>
  <li>Whenever an entry is pushed into <code>pq</code>, does it <strong>always</strong> become <code>b</code> element in <code>compfunc</code>?</li>
  <li>If (1) is correct, then when I push <code>6</code> in <code>pq</code>, <code>a = 5</code> and <code>b = 6</code>. And the return is <code>true</code> i.e., <code>5 &lt; 6</code>, meaning that <code>5</code> goes before <code>6</code> in <code>pq</code>, but in fact <code>6</code> should become the <code>top</code> of <code>pq</code>.</li>
  </ol>
  <p>I'm puzzled on (2) and how the <code>Compfunc</code> comparison works.</p>