[英]Cast an iterator to another type
我正在使用OpenGL进行渲染。
我上了一堂课,几何:
class Geometry
{
public:
void setIndices( const unsigned int* indices, int indicesCount );
private:
std::vector<unsigned char> colors;
std::vector<float> positions;
std::vector<unsigned int> indices;
};
有时,我的几何图形需要存储具有不同类型的索引,数据可以是:
1. std::vector<unsigned char>
2. std::vector<short>
3. std::vector<int>
// I've already think about std::vector<void>, but it sound dirty :/.
当前,我在所有地方都使用unsigned int ,并且在要将数据设置为几何体时强制转换数据:
const char* indices = { 0, 1, 2, 3 };
geometry.setIndices( (const unsigned int*) indices, 4 );
稍后,我想在运行时更新或读取此数组(有时数组可以存储60000多个索引),所以我要执行以下操作:
std::vector<unsigned int>* indices = geometry.getIndices();
indices->resize(newIndicesCount);
std::vector<unsigned int>::iterator it = indices->begin();
问题是我的迭代器在一个无符号的int数组上循环,所以迭代器将goto 4个字节变为4个字节,我的初始数据可以是char(所以1个字节至1个字节)。 无法读取我的初始数据或用新数据更新它。
当我想更新向量时,我唯一的解决方案是创建一个新数组,用数据填充它,然后将其转换为一个无符号的int数组,我想对索引指针进行迭代。
谢谢你的时间!
转换为错误的指针类型会产生未定义的行为,并且如果指针的大小错误,则肯定会失败。
我该如何做一些通用的事情(使用unsigned int,char和short)?
模板是使该泛型成为最简单的方法:
template <typename InputIterator>
void setIndices(InputIterator begin, InputIterator end) {
indices.assign(begin, end);
}
用法(将示例更正为使用数组而不是指针):
const char indices[] = { 0, 1, 2, 3 };
geometry.setIndices(std::begin(indices), std::end(indices));
您可能会考虑一个方便的重载,可以直接获取容器,数组和其他范围类型:
template <typename Range>
void setIndices(Range const & range) {
setIndices(std::begin(range), std::end(range));
}
const char indices[] = { 0, 1, 2, 3 };
geometry.setIndices(indices);
如何在没有复制的情况下遍历数组?
如果不复制数据,则无法更改数组的类型。 为了避免复制,您必须期望正确的数组类型。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.