读取数字从文件到向量的向量的顶点
Reading numbers from file into a vector of vector of vertices
所以我试图将文本文件(未知大小)读取为我自己定义的类型的矢量: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.
参见修改语法的实例
相关文章:
- 如何循环打印顶点结构
- 写入向量<向量<bool>>
- 函数向量_指针有不同的原型,我可以构建一个吗
- std::向量与传递值的动态数组
- 将值指定给向量(2D)的向量中的某个位置
- 找不到成员对象:没有名为get_event()的成员,也处理多态性和向量
- 如何使用向量的template_back函数
- 尝试通过多个向量访问变量时,向量下标超出范围
- 如何通过派生类函数更改基类中的向量
- C++从另一个类访问公共静态向量的正确方法是什么
- 如何将ampl中的集合表示为c++中的向量
- 变量没有改变?通过向量的函数调用
- 迭代时从向量和内存中删除对象
- 如何从 2 个向量构建顶点矩阵?
- 通过查找重复顶点从 vec3 对象的向量计算索引
- C++ 提升图形库:构建在无向图形搜索中访问的顶点的向量
- 内在循环依赖C++顶点和向量
- 读取数字从文件到向量的向量的顶点
- 由向量的向量构成的有向图中的可达顶点
- 从图复制到向量后顶点数增加