【发布时间】:2018-07-23 20:46:56
【问题描述】:
我是 C++ 的新手,并使用 std::vector 编写了一个多项式类。一切正常,直到我尝试调用函数 getCoeff(int index) 应该返回特定索引处的系数。在我的情况下,getCoeff(0) 应该返回第 0 个系数,即“1”。
我在使用 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
多项式.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中不被接受谢谢你的帮助。
【问题讨论】:
-
不相关,但你知道
std::vector有复制构造函数和赋值运算符,对吧?您无需逐个复制元素。 -
@StoryTeller OP 必须使用反向迭代器,而不是直接复制结构。此外,dtor 中的
.clear()是不必要的。 -
@Borgleader - 很公平。但即便如此,
std::vector的迭代器接受 c'tor 以及assign成员也应该这样做。它会看起来更干净,IMO。 -
@Borgleader - 实际上,源向量的每个元素都被复制到目标向量中的相应位置。为什么不简单的分配或复制呢?