如何使用函数指针定义多集
How to define a multiset using a function pointer?
我在做C++Primer第五版的练习时被卡住了,这就像
练习11.11:在不使用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;
}
std::multiset的第二个模板参数需要函数的类型,而不是函数!
这将起作用:
#include <set>
struct A{};
bool compareA(const A &a1, const A &a2)
{
return true;
}
int main()
{
std::multiset<A, bool (*)(const A&, const A&)> m1(compareA);
// or
typedef bool (*fp)(const A&, const A&);
std::multiset<A, fp> m2(compareA);
}
相关文章:
- 用户定义函数中的指针和输入
- 使用"Task"函数指针队列定义作业管理器
- 通过函数指针定义类范围之外的方法
- 共享指针和具有自定义删除程序的唯一指针之间的语法差异背后的任何原因
- 如何重新定义 C++ 指针函数?
- 返回对未定义指针的引用
- 为什么此自定义指针类会崩溃?
- 如何定义指针铸件操作员
- 定义指针随机崩溃该程序
- 在不同的文件(C++)中定义指针数组长度
- 如何定义指针和动态内存分配的模板
- 具有自定义指针类型的unique_ptr:*get() 和运算符*() 给出不同的输出
- 定义指针时不显示输出;
- 自定义指针类型和容器/分配器类型定义
- 并排定义指针和类型问题
- 具有自定义指针类型的内存分配器
- 正在对unordered_set的自定义指针类型进行哈希处理
- 查找全局定义指针指向的地址,该地址使用了堆分配
- 如何有效地计算已定义指针的数量
- 用户定义指针队列中的分段错误