使用std :: vector <int>的C ++多项式类的std :: out_of_range

时间:2018-02-13 13:05:11

标签: c++ c++11 vector

我对C ++很新,并使用std :: vector编写了一个多项式类。一切正常,直到我尝试调用函数getCoeff(int index),该函数应返回特定索引处的系数。在我的例子中,getCoeff(0)应该返回第0个系数,即&#39; 1&#39;。

相反,我在使用g ++进行编译时收到此错误:

terminate called after throwing an instance of 'std::out_of_range'
what(): vector::_M_range_check: __n (which is 0) >=this-> size() (which is 0)
Aborted

Polynomial.h:

#include<iostream>
#include<vector>

using namespace std;

class Polynomial
{
    public:
    Polynomial(int deg, std::vector<int> coeff);
    Polynomial(const Polynomial & p);
    ~Polynomial();
    const int getCoeff(int index);

    private:
    int degree;
    std::vector<int> coefficient;

};

Polynomial::Polynomial(int deg, std::vector<int> coeff)
{
    degree = deg;
    std::vector<int> coefficient(deg);
    for( int i = degree; i >= 0; i--) 
        coefficient[i] = coeff[i];
}

Polynomial::Polynomial(const Polynomial & p)
{
    degree=p.degree;
    std::vector<int> coefficient(p.degree);
    for ( int i=p.degree; i>= 0; i-- )
        coefficient[i] = p.coefficient[i];
}

const int Polynomial::getCoeff(int index)
{
    return coefficient[index];
}

Polynomial::~Polynomial()
{
    //delete[] & coefficient;
    coefficient.clear();
}

主文件,我在其中创建了一个测试多项式test1,其度数为3,系数为1,9,3,4(注意:std :: vector coeff1是由数组ko1 []构成的):

int main ()
{
    int ko1[] = {1,9,3,4};
    int degree1 = sizeof(ko1)/sizeof(*ko1)-1;

    std::vector<int> coeff1;
    for (int i=0; i<= degree1; i++)
        coeff1.push_back(ko1[i]);

    Polynomial test1(degree1, coeff1);

    cout << "Coefficients: " << endl;
    for (int j=0; j<=degree1; j++)
    cout << coeff1[j] << endl;


    cout << test1.getCoeff(0); //this is where the error occurs

    return 0;

}

我怀疑构造函数中存在错误,或者在新的std :: vector中不接受从数组中获取的元素感谢您的帮助。

1 个答案:

答案 0 :(得分:4)

代码中的一个反复出现的错误是它假定向量具有索引为[0, size]的元素,而它是半开放范围[0, size)。例如。构造函数中的那些循环应该是for(int i = degree; i-- > 0;)for(int i = 0; i < degree; ++i),以避免在索引degree访问不存在的元素。

另一个原因是构造函数Polynomial(int deg, std::vector<int> coeff)无法初始化coefficient成员变量,而是初始化一个局部变量。修正:

Polynomial::Polynomial(int deg, std::vector<int> const& coeff)
    : degree(deg)
    , coefficient(coeff)
{}

由于degree是系数的数量,您可以删除成员degree并使用coefficient.size()代替它。

代码不需要自定义复制构造函数或析构函数,您可以安全地删除它们,或者在必要时将它们声明为= default