c++ - 如何使用函数指针定义多重集?

标签 c++ stl function-pointers

我在做 C++ Primer 5th Edition 的练习时卡住了,就像

Exercise 11.11: Redefine bookstore without using decltype.

本书相关代码如下:

multiset<Sales_data, decltype(compareIsbn)*> bookstore(compareIsbn);

类 Sales_data 的代码在这里发布有点冗长,所以我写了一个更简单的代码并以相同的样式定义了 multiset,如下所示。它编译没有任何错误。

class A
{
    int lenth;
public:
    int getLenth() const {return lenth;}
};

bool compareA(const A &a1, const A &a2)
{
    return a1.getLenth() < a2.getLenth();
}

int main()
{
    std::multiset<A, decltype(compareA)*> m1(compareA);
    return 0;
}

我想这个练习是想让读者复习函数指针的知识,所以我尝试了另一种定义方式。但它不起作用。下面是我卡住的地方

int main()
{
    bool (*fp) (const A &a1, const A &a2);
    fp = &compareA;

    std::multiset<A, fp*> m1(fp);

    return 0;
}

产生了三个错误:

error: template argument 2 is invalid
error: invalid type in declaration before '(' token
error: invalid conversion from 'bool (*)(const A&, const A&)' to 'int' [-fpermissive]

我的问题是什么?如何解决?

最佳答案

你很接近,但需要在公开场合进行类型争论 <>括号而不是指针

typedef bool (*fp) (const A &a1, const A &a2);
int main() {    
    std::multiset<A, fp> m1(&compareA);

    return 0;
}

或者

bool (*fp) (const A &a1, const A &a2) = compareA;
int main() {    
    std::multiset<A, bool (*) (const A &, const A &)> m1(fp);

    return 0;
}

使用更新的编译器,您可以通过使用高阶函数内联定义比较器:

using comparator = std::function<bool(const A&, const A&)>;

auto main() -> int {    
    std::multiset<A, comparator> m1([](const A& a1, const A& a2) -> bool {
         return a1.getLenth() < a2.getLenth();
    });
    return 0;
}

关于c++ - 如何使用函数指针定义多重集?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20627530/

相关文章:

C++ 模板和重载运算符

c++ - 从另一个线程修改 vector 中的指针数据是否安全?

C++字符串拆分但转义引号中的所有定界符

c++ - 将在类中声明的函数作为参数传递会导致编译错误

c++ - 函数指针类型之间的转换

c++ - 函数指针如何替代 switch 语句?

c++ - 通过键 vector 从 map 获取 map

c++ - c++中奇怪的语法是什么意思

外部声明的全局对象的 C++ 链接器错误

c++ - 我应该如何使用remove_if删除两个数字范围内的元素