如何使用函数指针定义多重集? [英] How to define a multiset using a function pointer?
问题描述
我在进行 C ++ Primer 5th Edition 练习时陷入困境,就像
I'm stuck when doing an exercise from C++ Primer 5th Edition ,which goes like
练习11.11:不使用decltype重新定义书店.
Exercise 11.11: Redefine bookstore without using decltype.
以下是本书中的相关代码:
Below is the relevant codes in this book:
multiset<Sales_data, decltype(compareIsbn)*> bookstore(compareIsbn);
Sales_data类的代码在此处有些冗长,因此我编写了一个简单的代码,并以相同的样式定义了多集,如下所示.它编译没有任何错误.
The code for class Sales_data is a little bit verbose to post here,so I wrote a simpler one and defined the multiset in the same style, as shown below. It compiled without any error.
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;
}
我猜想本练习希望读者回顾一下函数指针的知识,因此我尝试了另一种定义它的方法.但这是行不通的.下面是我被困住的地方
I guess this exercise want readers to review knowledge of function pointers, so I tried another way to define it. But it doesn't work. Below is where I'm stuck
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]
我有什么问题?如何解决?
What's my problem?How to fix it?
推荐答案
您很近,但是需要在<>
括号中而不是在指针中使用类型争论
You were close, but needed a type arguement in the open <>
brackets rather than a pointer
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;
}
使用更新的编译器,您可以通过使用高阶函数来内联定义比较器:
With a more recent compiler, you can define the comparator inline through the use of higher-order functions:
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;
}
这篇关于如何使用函数指针定义多重集?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!