简体   繁体   English

为什么在 Class 或 Struct 中传递自定义比较器函数?

[英]Why custom comparator functions are passed in Class or Struct?

I am writing a priority queue that has its own comparator function. Every where I see following implementation and not able to figure out what's the rationale behind defining comparator function in class or struct?我正在编写一个优先级队列,它有自己的比较器 function。我看到以下实现的每个地方都无法弄清楚在 class 或结构中定义比较器 function 的基本原理是什么?

struct CompareHeight { 
    bool operator()(pair<int, int> const p1, pair<int, int> const p2) 
    { 
        if(p1.first == p2.first)
            return p1.second > p2.second; 
        return p1.first < p2.first; 
    } 
}; 

int main(){
    priority_queue<pair<int, int >, vector<pair<int,int> >, CompareHeight> p;
}

Edit 1 - why use class or struct directly define a comparator function just like main function and used it?编辑 1 - 为什么使用 class 或 struct 直接定义一个比较器 function 就像 main function 一样并使用它?

Why custom comparator functions are passed in Class or Struct?为什么在 Class 或 Struct 中传递自定义比较器函数?

Classes are often used rather than the alternative - function pointer that is - because doing so is potentially faster.通常使用类而不是替代方法——function 指针——因为这样做可能更快。 A function pointer is inherently a form of runtime polymorphism. function 指针本质上是运行时多态性的一种形式。 It is sometimes impossible, or just too difficult for an optimiser to determine at call time, what function is going to be called.有时,优化器无法在调用时确定 function 将被调用什么,或者对于优化器来说太难了。

By contrast, the member function operator overload of a class is known at compile time because the class is known at compile time.相比之下,class 的成员 function 运算符重载在编译时是已知的,因为 class 在编译时是已知的。 At minimum, there is advantage of not having to indirect through a pointer to make the call.至少,有一个优点是不必通过指针间接进行调用。 In some cases, this may even open door to inline expansion and through that, other optimisations.在某些情况下,这甚至可能为内联扩展打开大门,并通过它进行其他优化。

Function objects also have the advantage of being able to store data across their invocations, although there isn't always need to take advantage of that possibility. Function 对象还具有能够跨调用存储数据的优势,尽管并不总是需要利用这种可能性。


PS It is often better to generate the function object class using a lambda instead of writing it explicitly. PS 通常最好使用 lambda 生成 function object class 而不是显式写入。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM