Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

C+ selective predefined functor initializaiton

Predefined functors need to be in-place instantiated (with empty parentheses) for use in algorithms but not as type parameters for container adapters such as priority_queue. Why the difference?

#include <queue>
#include <vector>
#include <numeric>

int main(){

   std::priority_queue<int, std::vector<int>,
   // parentheses are NOT neded here: std::greater<>
                                            std::greater<>> pq;
   pq.push(1);
   pq.push(2);
   pq.push(3);

   std::vector<int> v = {1, 2, 3};

   auto result = accumulate(v.begin(), v.end(), 0,
                              // parentheses are needed here std::plus<>()
                                                  std::plus<>());
}

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

std::priority_queue is a class template with type template parameters. Its specialization requires to specify type template arguments. And std::greater<> is a type used as a type template argument.

On the other hand, in an algorithm you need to supply a functional object as for example std::greater<>().

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading