2

我每帧生成一个值集合,我想将这些值添加到特定索引处的更大值集合中。

这是我正在生成的集合的典型示例

std::vector<glm::vec3> corners;
corners.reserve(8);
//glm::vec3 corners[8];
//std::list<glm::vec3> corners;

corners[i++] = position - hX + hY + hZ;
corners[i++] = position + hX + hY + hZ;
corners[i++] = position + hX - hY + hZ;
corners[i++] = position - hX - hY + hZ;
corners[i++] = position - hX + hY - hZ;
corners[i++] = position + hX + hY - hZ;
corners[i++] = position + hX - hY - hZ;
corners[i++] = position - hX - hY - hZ;

然后我有一个更大的 glm::vec3 值集合,我想将上面的值复制到特定索引处。

std::vector<glm::vec3> vertices;
vertices.assign(maxVertices, 0);

C# 等价物是

corners.CopyTo(vertices, index);

我可以使用什么类类型来有效地生成较小的集合并将其复制到较大的集合,而不会在每一帧生成它的开销太大?

我可以将每个新生成的较小集合分配到较大集合的末尾,这样可以忽略索引值。

4

2 回答 2

2

在您的代码中,您应该corners.resize(8),而不是corners.reserve(8)。此外,如果我理解正确,您似乎总是有 8 个角?然后使用数组:

typedef std::array<glm::vec3, 8> Corners; 
// or in pre-c++0B code use boost::array same way
// or if neither is available then just raw glm::vec3[8] can do.

然后可以通过初始化完成填充:

// somehow we have position, hX, hY and hZ
Corners corners =
{
    position - hX + hY + hZ,
    position + hX + hY + hZ,
    position + hX - hY + hZ,
    position - hX - hY + hZ,
    position - hX + hY - hZ,
    position + hX + hY - hZ,
    position + hX - hY - hZ,
    position - hX - hY - hZ
};

可以使用标准副本进行复制:

std::vector<glm::vec3> vertices;
// somehow it gets filled

// somewhere comes index

std::copy( corners.begin(), corners.end(), vertices.begin() + index );
// with raw glm::vec3[8] std::copy( corners, corners + 8, vertices.begin() + index );

如果您需要插入而不是复制,请使用 vertices.insert()

于 2012-08-25T23:45:54.613 回答
1

您可以使用vector::insert. 如果你想在向量中的corners位置之前插入值,你可以这样做:indexvertices

vertices.insert(vertices.begin() + index, corners.begin(), corners.end());

但是,该操作需要为新值腾出空间。这会将所有元素从index向量的末尾转移(也许也需要调整向量的大小)。

为了避免这种情况,您可以使用 alist代替。

于 2012-08-25T23:47:34.630 回答