C++,尝试编写对象读取器,尝试从一个 vector 获取数据时出错

标签 c++ vector vertices outofrangeexception face

我正在尝试编写一个非常简单的 obj 文件读取器,它将 obj 文件中的所有顶点值按顺序写入一个 vector (已经完成),并将 obj 文件中由面值引用的顶点值写入另一个 vector vector ,例如:

v1 = 0.0 0.0 0.0

v2 = 1.0 0.0 0.0

v3 = 1.0 1.0 0.0

f1 = 3 2 1

我的程序会在第一个 vector 中按顺序写入所有顶点值 然后在第二个 vector 中写入构成面的顶点值,如下所示: 1.0 1.0 0.0 1.0 0.0 0.0 0.0 0.0 0.0

一切正常,直到我尝试从第一个 vector (verticesCoordsXYZ) 获取值并将它们推回第二个 vector (faceCoords)。我注释掉的代码破坏了程序,似乎我在第一个 vector 中搜索的位置大于 vector 大小(当程序中断时,我在内存定位错误中得到 out_of_range,它说 verticesCoordsXYZ 的大小是0),即使我用所有顶点值填充了 vector 。

我做错了什么?我是否不了解 vector 的工作原理,我是否超出了 vector 范围?我该如何解决这个问题?

    string line;
    while (getline(modelfile, line))
    {

        string s;
        istringstream iss(line);
        iss >> s;
        vector <float> verticesCoordsXYZ;
        vector <float> faceCoords;

        if (s == "v")
        {

            float x, y ,z;
            iss >> x >> y >> z;
            verticesCoordsXYZ.push_back(x);
            verticesCoordsXYZ.push_back(y);
            verticesCoordsXYZ.push_back(z);

            for (int i = 0; i < (int)verticesCoordsXYZ.size(); i++)
            {
                cout << verticesCoordsXYZ.at(i);
            }
            cout << endl;

        }

        if (s == "f")
        {
            int a, b, c;

            iss >> a >> b >> c;

            int aLocation = a * 3 - 3; //vertice locations in verticeCoordsXYZ that would make up faces
            int bLocation = b * 3 - 3;
            int cLocation = c * 3 - 3;

            for (int i = 0; i < 2; i++)
            {
                //faceCoords.push_back(verticesCoordsXYZ.at(aLocation+i));
            }
            for (int i = 0; i < 2; i++)
            {
                //faceCoords.push_back(verticesCoordsXYZ.at(bLocation+i));
            }
            for (int i = 0; i < 2; i++)
            {
                //faceCoords.push_back(verticesCoordsXYZ.at(cLocation+i));
            }

            for (int i = 0; i < (int)faceCoords.size(); i++)
            {
                cout << faceCoords.at(i) << "f";
            }



            cout << endl << a << b << c;
        }

    }

    modelfile.close();

最佳答案

您每次通过 while 循环都在重新创建 vector ,因为它们是在其中声明的。这意味着当 s == "f" 它们都是空的。

您应该在 while 循环之外声明它们,您在其中声明 line

关于C++,尝试编写对象读取器,尝试从一个 vector 获取数据时出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35901714/

相关文章:

c++ - boost 灵气——条件解析

c++ - 在调试器中自动显示具有已知类型和长度的 void*(数组)

c++ - 注册变量

string - 在 Rust 中加入字符串向量

c++ - 是否保证 C++ vector v 的 v.begin() + v.size() == v.end() ?

object - 手动读取 .ply 文件

c++ - 时区之间的时间转换

Python:列表列表中的组合(?)

c# - 如何用不同大小的四边形填充程序生成的网格?

c++ - 将继承类对象的 vector 传递给需要基类 vector 的函数