向量下标超出范围的多维向量

时间:2015-12-18 20:13:53

标签: c++ vector multidimensional-array containers

我正在研究PLY文件阅读器(带有顶点和面部位置信息的txt文件)。它由标题,顶点位置,面信息组成。

-1 -1 -1 // x y z坐标

3 1 2 3 //这张脸由3个顶点组成 - 1,2,3

之后我用OpenGL绘制它。

我使用数组,现在我想使用矢量容器来节省价值。因为在编译期间我不必知道大小。

我初始化了两个载体:

vector<string> ply_file;
vector< vector<float> > vertex_list;

使用ply_file一切正常,但是当我尝试用这段代码写入vertex_list时:

int j = 0;  
for(int i=first_vertex_row-1;i<first_vertex_row+vertex_number-1;i++)
{       
    std::stringstream ss(ply_file[i]); 
    ss >> vertex_list[j][0] >> vertex_list[j][1] >> vertex_list[j][2]; // x,y,z     
    j++;
}

但我得到调试断言失败:向量下标超出范围。

我知道我是以错误的方式写作,但我无法让它发挥作用。 是否可以使用stringstream将其写入多维向量?如果是这样,如何实现呢?

1 个答案:

答案 0 :(得分:1)

vector< vector<float> > vertex_list;创建一个空向量。当您尝试使用

将值插入其中时
ss >> vertex_list[j][0] >> vertex_list[j][1] >> vertex_list[j][2];

所有这些索引都超出了向量的范围。为了像这样向向量添加值,您需要将其构造为所需的大小。对于2d向量,它将具有

的形式
std::vector<std::vector<some_type> some_name(rows, std::vector<some_type>(columns, value));
相关问题