将紧凑型float值数组转换为float数组的更简洁方法 [英] Cleaner way to convert an array of compact float values into an array of floats

查看:52
本文介绍了将紧凑型float值数组转换为float数组的更简洁方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在提出实际问题之前,先做个小前奏.我不在乎安全性,我在乎性能.我知道这是不合适的,而且我知道这很hacky,但是速度很快.

Before the actual question, small prelude. I don't care about security, I do care about performance. I KNOW this is not proper and I know it's very hacky, however this is quite fast.

vector< float>结果= move(*(((vector&float> *)& vertices));

该代码滥用C样式强制转换和指针,以迫使编译器解释左侧数组 vertices ,这是紧凑型向量,其中所有字段都以float数组形式浮动

That code is abusing C style casts and pointers to force the compiler to interpret the left hand side array vertices which is a vector of a compact type where all the fields are float as an array of floats.

struct vertex {
   float x;
   float y;
   float z;
}
vector<vertex> vertices;

这有效并且可以完成所需的工作,但是有点难以理解.我想知道是否还有另一种以更易读的方式实现相同结果的方法.

This works and does what it needs to, however it's somewhat hard to read. I want to know if there is another way of achieving the same outcome in a more readable way.

推荐答案

您应该更关心的是代码的行为是 undefined ,因为强制类型转换违反了严格的别名规则.请注意, vector< vertex> 是与 vector&float> 完全不同的 类型.

What you should care more about is that the behaviour of your code is undefined since the cast is a violation of the strict aliasing rule. Note that vector<vertex> is a completely different type to a vector<float>.

特别是,您假设 struct 中的数据是连续的,并且即使在最后, struct 中也没有填充.

In particular you are assuming the data in the struct are contiguous and there is no padding in the struct, even at the end.

为什么不从一开始就使用 vector< float> ,并要注意,第4个元素会开始下一个三角形,依此类推?

Why not use a vector<float> from the get-go, with a note to self that the 4th element starts the next triangle, and so on?

这篇关于将紧凑型float值数组转换为float数组的更简洁方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆