如果它不是函数指针,它是什么?

时间:2014-03-07 01:14:03

标签: c++ function-pointers

首先,我发现priority_queue<int>会给更大的整数提供更高的优先级。 如果我们使用priority_queue<int, vector<int>, greater>,那么它会反过来。为什么呢?

此外,我们放入优先级队列的比较器似乎不是函数指针。相反,它被定义为:

struct cmp{
    bool operator() (const int& lhs, const int&rhs) const
    {
        ...
    }
}

我听说这是C ++非常有用的属性;任何人都可以向我解释这种类型的代码吗?

3 个答案:

答案 0 :(得分:2)

这是仿函数。它基本上是一个类/对象,它通过重载operator()来充当函数。例如,在您的代码中,您可以这样做:

cmp func;
func(1, 2);
// ^ calls operator()

您可以阅读有关他们的更多信息here

答案 1 :(得分:0)

这种代码的好处是,如果类型是模板化的,你可以放入一个函数指针或类似上面的类(一个函子)。在任何一种情况下,它们都可以工作,第一种更简单,而第二种则可以提供数据。 c ++ 11中的Lambdas使它们有点多余。

答案 2 :(得分:0)

Functors通常用于在算法中维护 state 。请考虑以下搜索功能:

struct Foo { int x };
std::vector<Foo> fooList; // Imagine this is populated.

struct FindFunc
{
    FindFunc(int toFind) : val(toFind) {}
    bool operator()(const Foo& el) { return el.x == val; }
    int val;
};

// Seach the list of Foo objects for one where member x is 42
std::find_if(fooList.begin(), fooList.end(), FindFunc(42));