【问题标题】:how to use function object with an array?如何将函数对象与数组一起使用?
【发布时间】:2018-01-25 03:36:52
【问题描述】:

我想写一个 C++ 通用算法,它可以在集合、列表、映射、向量等上工作......所以这个算法接受一个容器和一个函数对象,所以我可以检查某些条件。

该算法需要根据一定的条件检查容器中最长的序列并返回其长度。

我在将函数对象传递给函数时遇到了问题,因为我收到了这个错误(在 main 的第二行):

"此行有多个标记 - 无效参数 ' 候选者是:void functionA(#0 &, #0 &, #1) ' - 从 'std::array::iterator {aka "

类型的右值对 'int*&' 类型的非常量引用的初始化无效

我不明白这个问题,因为在函数对象中有一个运算符 () :\ 即使我先调用构造函数,我仍然会得到这个错误..

我尝试了什么:

template<typename T,typename Predicate>
void functionA(T& it1 , T& end1,Predicate pred){
    for(;it1 != end1; ++it1){
        T it2=it1++;
        if(!pred(*it1,*it2)){
            std::cout << *it1 << "\n" ;
            return;
        }
        }
    std::cout <<"not found" << "\n" ;
}

class FindFirst {
    public:
    FindFirst();
    bool operator()(int f , int s) const {
       return f < s;
    }
};

int main() {

    std::array<int,11> myarray = {1,2,4,7,10,14,3,6,12,24,48};
    functionA(myarray.begin(),myarray.end(),find);

}

【问题讨论】:

    标签: c++ arrays algorithm


    【解决方案1】:

    问题是std::array::begin按值返回,这是一个临时的,不能绑定到对非const的左值引用(即T&amp;)。

    functionA的参数类型改为传值,例如

    template<typename T,typename Predicate>
    void functionA(T it1 , T end1,Predicate pred){
    

    LIVE

    【讨论】:

    • 我现在收到此错误:未定义对 `FindFirst::FindFirst()' 的引用
    • @mamama 你需要定义它,构造函数。如果你没有什么要实现的,你可以删除声明。
    • @mamama 恭喜;至少你有预付款。
    猜你喜欢
    • 2020-09-24
    • 2016-04-17
    • 1970-01-01
    • 2020-10-13
    • 2016-04-11
    • 2017-06-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多