读取数字从文件到向量的向量的顶点

Reading numbers from file into a vector of vector of vertices

本文关键字:向量 顶点 文件 数字 读取      更新时间:2023-10-16

所以我试图将文本文件(未知大小)读取为我自己定义的类型的矢量:Vertex(包含float x,y,z)。所以,当一切都说了,做了,coordpts中的每一行(向量的向量的变量)应该代表被读入的对象的一个面,因此应该有几组xyz坐标。

我正在工作的前提是文件中的每一行被读取代表一个面(立方体,茶壶,任何物体)。

我知道我应该把每一组三个坐标推回一个临时向量,然后把这个临时向量推回coordpts,但是我在访问元素时遇到了麻烦?

当我执行上述操作时,我的代码可以编译,但是每当我尝试访问一个元素时,我都会得到错误。

我错过了一些明显的东西吗?

我主要只是想打印出数据,这样我就可以看到我是否正确地读取了它(也因为我以后必须在其他函数中访问它)。

头文件:

#include <iostream> // Definitions for standard I/O routines.
#include <fstream>
#include <cmath>    // Definitions for math library.
#include <cstdlib>
#include <string>
#include <vector>
#include <list>
using namespace std;
class Vertex {
public:
    Vertex() {};
    float x, y, z; // float to store single coordinate.
};
class Object : public Vertex {
public:
    Object() {};
    vector<vector<Vertex>> coordpts; // vector of x, y, z floats derived from vertex class.
    // vector<Vertex> coordpts;
};

程序文件:

(我知道main不在那里,我已经把它包含在另一个文件中了)

#include "header.h" // Include header file.
Object object;
string inputfile;
fstream myfile;
void Raw::readFile() {
     vector<Vertex> temp;
    cout << "Enter the name of the file: ";
    cin >> inputfile;
    myfile.open(inputfile);
    if(myfile.is_open()) {
        while(myfile >> object.x >> object.y >> object.z) {
            temp.push_back(object);
            object.coordpts.push_back(temp);
        }
    }
    myfile.close();
    cout << object.coordpts[0] << endl;
};
cout << object.coordpts[0] << endl;

这里你试图输出"顶点向量的向量"的第一个元素,例如。,您正在尝试输出std::vector<Vertex>。这将导致错误,因为接受顶点向量的输出操作符没有重载。

错误:'operator<<'不匹配(操作数类型为'std::ostream'和'std::vector')

如果你想,,输出coordpts中第一个std::vector中第一个顶点的x值,那么你必须这样做。

std::cout << object.coordpts[0][0].x << std::endl;

或者,您可以简单地创建自己的重载来输出std::vector<Vertex>行/面。

std::ostream& operator<<(std::ostream& out, const std::vector<Vertex>& face) {
    for (auto&& v : face) {
        out << v.x << " " << v.y << " " << v.z << std::endl;
    }
    return out;
}
/* ... */
std::cout << object.coordpts[0] << std::endl; // Ok, output first row/face.

参见修改语法的实例