gpt4 book ai didi

c++ - 在泛型函数中使用仿函数

转载 作者:行者123 更新时间:2023-12-02 10:29:05 27 4
gpt4 key购买 nike

我已经构建了一个通用函数,它采用某个容器(使用迭代器作为其开始和结束)和一个谓词(作为某种条件检查的仿函数)并计算该容器中为真的对数谓词条件。
如下

//Counts number of pairs in a container that follow the rule of the Predicate
template <typename Iterator, typename Predicate>
int countPairs(const Iterator first, const Iterator last, Predicate pred){
int counter = 0;
for(Iterator current = first; current<last; ++current){
Iterator next(current);
for(++next; next<last; ++next){
if(pred(*current, *next)){
counter++;
}
}
}
return counter;
}
然后,我想使用通用函数来检查某个 vector 是否已排序。因此,我构建了以下“谓词”,用于检查一对数字是否已排序:
bool isBigger(int a, int b){
return b < a;
}
然后,我构建了一个名为的函数,该函数基本上使用上述两个函数来获取 vector 并检查其是否已排序:

bool isSorted(std::vector<int>& v){
int size = v.size();
if(size == 0 || size == 1){
return true;
}
return countPairs(v.begin(), v.end(), isBigger()) == 0;
}
当我尝试构建时,如果为我提供以下错误:

error: no matching function for call to 'isBigger'

note: candidate function not viable: requires 2 arguments, but 0 wereprovided


我很确定这是因为我使用 isBigger 的方式 countPairs 中的函数打电话。但这就是通用代码的工作方式,不是吗?
非常感谢你。

最佳答案

如果您仔细阅读错误:

error: no matching function for call to 'isBigger'
note: candidate function not viable: requires 2 arguments, but 0 were provided


您将立即意识到出了什么问题。而不是将函数作为参数传递,以便可以在此处调用它:
            if(pred(*current, *next))
您改为调用该函数。
修复很简单,而不是
return countPairs(v.begin(), v.end(), isBigger())
传递函数的地址:
return countPairs(v.begin(), v.end(), &isBigger)
此外,您还写道:

Predicate (functor which serves as a some sort of condition check)


但是您没有使用任何仿函数。仿函数只是一个定义 operator() 的类。 .在您的情况下,您仅使用普通功能。仿函数看起来像这样:
struct _isBigger{
bool operator()(int a, int b){
return b < a;
}
};

//and pass it to some function
return countPairs(v.begin(), v.end(), isBigger{})
旁注:您也可以使用 λ相反,它基本上就像一个没有名字的函数:
return countPairs(v.begin(), v.end(), [](int a, int b){
return b < a;
}) == 0;
如此美丽,对吧? ;)
此外,您的函数不会更改 vector范围:
bool isSorted(std::vector<int>& v){
所以,让它 const :
bool isSorted(const std::vector<int>& v){

关于c++ - 在泛型函数中使用仿函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63079428/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com