【问题标题】:Class with recursive method using int vector element as input使用 int 向量元素作为输入的递归方法类
【发布时间】:2017-09-10 06:39:25
【问题描述】:

我正在尝试创建一个具有递归二元运算符的类,该类从向量中获取输入,但由于某种原因,我一直出现以下错误:

||=== Build file: "no target" in "no project" (compiler: unknown) ===|
In member function 'int ReduceGeneric::reduce(std::vector<int>&, std::vector<int>::iterator)':|
|14|error: no matching function for call to 'ReduceGeneric::binaryOperator(std::vector<int>::iterator, int&)'|
|14|note: candidate is:|
|8|note: virtual int ReduceGeneric::binaryOperator(int, int)|
|8|note:   no known conversion for argument 1 from 'std::vector<int>::iterator {aka __gnu_cxx::__normal_iterator<int*, std::vector<int> >}' to 'int'|
|16|error: invalid cast to abstract class type 'ReduceGeneric'|
|4|note:   because the following virtual functions are pure within 'ReduceGeneric':|
|8|note:     virtual int ReduceGeneric::binaryOperator(int, int)|
|22|error: invalid cast to abstract class type 'ReduceGeneric'|
||=== Build failed: 3 error(s), 0 warning(s) (0 minute(s), 0 second(s)) ===|

这是代码:

#include <iostream>
#include <vector>

class ReduceGeneric {
public:
    int reduce(std::vector<int>& v, std::vector<int>::iterator i); //set i=v.begin() in main
private:
    virtual int binaryOperator(int m, int n) =0;
    int result;
};

int ReduceGeneric::reduce(std::vector<int>& v, std::vector<int>::iterator i)   {
    if (i==v.begin())   {
        result=binaryOperator(v.begin(),*i);
        i++;
        return ReduceGeneric(v,i);
    } else if (i==v.end()) {
        return result;
    }   else    {
        result=binaryOperator(result,*i);
        i++;
        return ReduceGeneric(v,i);
    }
}

class ReduceMinimum : public ReduceGeneric  {
private:
    int binaryOperator(int m, int n);
};

int ReduceMinimum::binaryOperator(int i, int j) {
    if (i<=j)   {
        return i;
    }   else    {
        return j;
    }
}

非常感谢。我是编程新手,所以任何输入都是很好的输入。显然,我的帖子充满了代码,所以我正在尝试添加更多文本。我喜欢披萨。

【问题讨论】:

  • 就像错误所说的那样,您正在尝试将迭代器分配给 int 参数。 v.begin() 是一个迭代器。您可以使用 front() 或使用 * 访问迭代器

标签: c++ class recursion vector


【解决方案1】:

您需要更改这些行以成功构建:

result=binaryOperator(v.begin(),*i);

result=binaryOperator(*v.begin(),*i);

正如@o_weisman 提到的那样。

两行:

return ReduceGeneric(v,i);

return ReduceGeneric::reduce(v,i);

因为你需要调用函数而不是类。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-05-01
    • 1970-01-01
    • 2016-06-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多