【发布时间】:2017-01-31 03:57:19
【问题描述】:
我正在编写一个程序,我需要使用以下数据结构:
struct shape
{
std::vector<float> verts; // contains the x & y values for each vertex
char type; // the type of shape being stored.
float shapeCol[3]; // stores the color of the shape being stored.
float shapeSize; // stores the size of the shape if it is a line or point
};
在我的主程序中,我需要一个shape 类型的向量。如何使用结构形状的向量将值存储到结构形状内部的向量中。
例如,vector<shape> myshapes;
如果我想将一个值存储到我的verts 向量的第一个索引中,在我的myshapes 向量的第一个索引内,我该怎么做?
在伪代码中它看起来像这样,i 是索引:
myshapes[i].vector[i] = 4; // but I know this is incorrect
使用 STL 列表是否会更容易实现?如果是,该语法是什么样的?
感谢您的帮助,我是矢量新手,所以任何建议都将不胜感激。
【问题讨论】:
-
您需要将
i替换为循环中使用的实际变量。也许myshapes[0].vector[0]=4; -
myshapes[index of shape].verts[index of vertex within that shape] -
语法与
std::list相同;区别在于它们在不同场景下的实现和性能。 -
std::vector[] 仅用于读取(右值),即数据可用。在使用 std::vector.push_back 或其他函数读取数据之前,您必须将数据添加到向量中。
-
@qxz,对不起,std::vector::operator[] 不仅适用于右值,我错了。我的意思是他应该首先使用 push_back 或其他功能来添加项目。您不能使用 operator[] 在数组中添加新项目。只是考虑到他是矢量的新手。