开发者

std::vector out of range

开发者 https://www.devze.com 2023-03-07 20:19 出处:网络
Currently I am trying to render a .obj model that I loaded into vectors. I am trying to pull the Vector3D object out of the array but it gives me an out of range error. It only goes to five before the

Currently I am trying to render a .obj model that I loaded into vectors. I am trying to pull the Vector3D object out of the array but it gives me an out of range error. It only goes to five before the array crashes, when the array has 12 objects for example. Here is the code for the rendering.

glBegin(GL_TRIANGLE_STRIP);

for (int indx = 0; indx < mv3_faces.size(); ++indx)
{
    if (mb_print_once)
    {
        std::cout << "Rendering L开发者_开发知识库oop....Faces at 8: " << mv3_faces.at(5).x << " Current Index: " << indx << std::endl;
        std::cout << "Rendering Loop X: " << mv3_faces.at(indx).x << " Y: " << mv3_faces.at(indx).y << " Z: " << mv3_faces.at(indx).z << std::endl;
    }

    glColor4f(1.0f, 1.0f, 0.0f, 1.0f);

    glVertex3f(mv3_vertices.at(mv3_faces.at(indx).x).x, mv3_vertices.at(mv3_faces.at(indx).y).y, mv3_vertices.at(mv3_faces.at(indx).z).z);
}

mb_print_once = false;
glEnd();

Ignore the mb_print_once... that is for debugging purposes.


Did you remember that vertex indices in .OBJ files start at 1 rather than 0? So you have to decrement the vertex indices by 1 after reading them from an "f" tag.

And also as a little comment, I would strongly suggest using [] instead of .at, although in this example it was a good idea, so you got the exception. But in general the range-checking overhead is not worth it, especially in such a highly to optimize loop.


My guess is that the exception comes from the mv3_vertices.at call: indx should be in range for mv3_faces, because of how that loop is made, so probably it's what is stored inside it that it's not a valid index for mv3_vertices.

If I were you I would step in with a debugger to find exactly whence the exception comes from (or you can split the glVertex3f(...) line in multiple statements and add some logging), and trace whence the bad data comes from.


glVertex3f(mv3_vertices.at(mv3_faces.at(indx).x).x, mv3_vertices.at(mv3_faces.at(indx).y).y, mv3_vertices.at(mv3_faces.at(indx).z).z);

I suspect this line.

Have you made sure that mv3_faces.at(indx).x < mv3_vertices.size() ? If that is not true, then you will get out of range exception. Check out the other two also; that is, mv3_faces.at(indx).y, and mv3_faces.at(indx).z.

Whenever you use std::vector::at() function, make sure that the index which you pass to at() is within range of the of the vector's size, otherwise at() will throw an out_of_range exception. If you don't make sure that, then use try-catch block to handle this exception and the rest of the program flow.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号