Comparators in STL

后端 未结 2 1731
醉话见心
醉话见心 2021-02-06 12:21

I am using struct minHeap to generate a min heap using priority_queue .And function comp to print numbers in reverse order using sort function given in STL . Now my doubt is tha

2条回答
  •  执笔经年
    2021-02-06 12:47

    What you are looking for in general is when to use functions or when to use functors.

    The short answer is: Use a functor if and only if you need to retain state across multiple calls to the operator. For comparison functions this is usually not the case, but there are other instances of uses such as accumulators, averagers, min/max calculators, etc.

    Another question that seems to cover similar ground and that may help you with more detail and some great references to external material: Comparison Functor Types vs operator<

    As to passing an actual function to priority_queue - it's not that obvious but it is possible:

    typedef bool(*CompareFunc)(float, float); // You need to have your function pointer 
                                              // type available
    bool Compare(float i_lhs, float i_rhs)    // The actual compare function matching the 
      {                                       // CompareFunc type
      // Do your compare stuff here.
      }
    
    ...
    std::priority_queue, CompareFunc> p(Compare);
    // Tell priorityqueue you're passing a compare *function*, and pass the actual function
    // as a parameter.
    

提交回复
热议问题