【问题标题】:Reading numbers from file into a vector of vector of vertices将文件中的数字读入顶点向量的向量
【发布时间】:2015-10-01 23:20:01
【问题描述】:

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

【问题讨论】:

  • 声明 “我遇到错误” 在这里不是一个有效的问题。请发minimal reproducible example
  • 什么错误,凯蒂?
  • 对不起,应该包括那个。当我尝试通过 object.coordpts[0].x 单独访问时,它在 'std::__1::vector >' 中没有名为 'x' 的成员(相同对于 y 和 z)。
  • 这里发生了一些奇怪的事情。您有一个全局Object,您反复更新并复制到一个临时文件中,该临时文件稍后被复制回同一Object 的成员中。为什么?为什么Object 首先继承自Vertex?并且不要使用全局变量。永远。

标签: c++ file-io vector


【解决方案1】:
cout << object.coordpts[0] << endl;

在这里,您尝试输出“顶点向量向量”的第一个元素,例如,您正在尝试输出std::vector&lt;Vertex&gt;。这将导致错误,因为输出运算符采用顶点向量没有重载。

错误:'operator')

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

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

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

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 修改语法。

【讨论】:

  • 好的,但是假设我想打印一整行(正在读取的某个对象的面)。就像,如果我正在读取一个包含立方体坐标的文件,那么一行将有 12 个单独的项目,四组,每组三个坐标。理想的输出应该是 '[[0, 0, 0], [1, 1, 1], [2, 2, 2], [3, 3, 3]]'...我可以通过创建我的自己的超载,就像你上面说的那样?
  • @Katie 是的,您可以通过 例如 自定义重载 &lt;&lt; 运算符来做到这一点。查看实时示例链接。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2013-11-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多