我正在做一个从基础和侧面输入创建等腰三角形的项目。然后我需要计算坐标并以一些可用的方式存储它们。我试图做的是创建一个顶点的2D矢量 - 所以一个3个坐标的数组,每个坐标有一个二维数组(x和y值)。当我尝试访问值(例如,用于翻译)时,我收到运行时错误:向量下标超出范围......
代码:
私人:
double base, side;
vector<double> coordA, coordB, coordC;
vector<vector<double> > vertex;
公共:
isoTri() : base(0), side(0), coordA(0), coordB(0), coordC(0) {}
isoTri(double base_in, double side_in) : base(base_in), side(side_in)
{
coordA.push_back(0); coordA.push_back(0); //bottom left corner at origin
coordB.push_back(base2); coordB.push_back(height); //top corner
coordC.push_back(base); coordC.push_back(0); //bottom right corner
vector<vector<double> > vertex{ 3 };
vertex[0] = { coordA }; vertex[1] = { coordB }; vertex[2] = { coordC }; //vector of coordinates
}
~isoTri() {}
void translate(double dx, double dy){
for (int i = 0; i < 2; i++){
for (int j = 0; j < 2; j++){
vertex[i][0] = vertex[i][0] + dx;
vertex[j][1] = vertex[j][1] + dy;
}
}
}; `
答案 0 :(得分:3)
vector<vector<double> > vertex{ 3 };
,声明一个名为vertex
的新局部变量,它与成员变量vertex
无关。它仍然是空的。你可以:
isoTri(double base_in, double side_in) : base(base_in), side(side_in)
{
coordA.push_back(0); coordA.push_back(0); //bottom left corner at origin
coordB.push_back(base2); coordB.push_back(height); //top corner
coordC.push_back(base); coordC.push_back(0); //bottom right corner
vertex.push_back(coordA);
vertex.push_back(coordB);
vertex.push_back(coordC);
}