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

时间:2015-10-01 23:20:02

标签: c++ file-io vector

所以我试图将一个文本文件(大小未知)读入我自己定义类型的向量向量: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;
};

程序文件:

(我知道主要没有,我已将其包含在另一个文件中。)

#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;
};

1 个答案:

答案 0 :(得分:-1)

cout << object.coordpts[0] << endl;

在这里,您尝试输出&#34;顶点向量矢量的第一个元素&#34;,例如,您正在尝试输出std::vector<Vertex>。这将导致错误,因为输出操作符没有过载顶点矢量的重载。

  

错误:&#39;运营商&lt;&lt;&lt;&# (操作数类型是&#39; std :: ostream&#39;和&#39; std :: vector&lt; Vertex&gt;&#39;)

如果你想,例如,输出std::vector中第一个coordpts的第一个顶点的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.

使用修改后的语法查看 Live example

相关问题