查找glm :: vec3阵列的尺寸
我有这个 glm :: vec3
数组,我想知道数组的大小:
glm::vec3 cubePositions[] = {
glm::vec3(0.0f, 0.0f, 0.0f),
glm::vec3(2.0f, 5.0f, -15.0f),
glm::vec3(-1.5f, -2.2f, -2.5f),
glm::vec3(-3.8f, -2.0f, -12.3f),
glm::vec3(2.4f, -0.4f, -3.5f),
glm::vec3(-1.7f, 3.0f, -7.5f),
glm::vec3(1.3f, -2.0f, -2.5f),
glm::vec3(1.5f, 2.0f, -2.5f),
glm::vec3(1.5f, 0.2f, -1.5f),
glm::vec3(-1.3f, 1.0f, -1.5f)
};
到目前为止,大小为10,但是有办法在代码中找到它吗?
我已经尝试了 cubeposits-> length()
,但它只给了我的值3。
我尝试过 glm :: length(cubepositions)
,但看起来不像那就是您如何使用 glm ::长度
函数。这种方式给出了一个错误。
谢谢您的帮助!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
Cubepositions
是C样式数组。它衰减到指向glm :: vec3
的指针。请参阅此处有关数组到指针衰减的信息:什么是指针衰减的数组?。因此,当您使用
cubepositions-> length()
相当于使用cubeposits [0] .length()
,它返回了第一个元素的GLM长度(即3因为它是vec3
)。为了获取数组中的元素数量,在这种情况下,您可以使用:
注意:仅在
cubepositss
定义的范围中起作用,因为仅知道数组的实际大小。它将不再工作,例如,如果将cubeposits
传递给另一个功能,因为那样的数组将腐烂到指针,并将“松动”它的大小。但是 - 这不是在C ++中进行的推荐方法。
最好使用
std :: vector
vector 用于动态大小数组。它有一种方法:
size> size> size>
要检索元素的数量:注意:如果您的数组的尺寸固定(在编译时已知),您也可以使用
std :: array
。它还具有size()
方法,尽管在这种情况下,它不那么有用,因为大小不能动态变化,实际上是模板参数之一。更新::
正如@HolyBlackCat所说的那样
std :: size
获取数字旧C数组中的元素:如果您通过腐烂的指针而不是真实的数组,则不会编译。请记住,正如我在上方写的那样,您最好避免使用旧的C数组。
cubePositions
is a C style array. It decays to a pointer toglm::vec3
. See here about array to pointer decay: What is array to pointer decay?.Therefore when you use
cubePositions->length()
it's equivalent to usingcubePositions[0].length()
, which returns the glm length of the first element (i.e. 3 because it's avec3
).To get the number of elements in the array in this case you can use:
Note: this will work only in the scope where
cubePositions
is defined because only there the real size of the array is known. It will no longer work e.g. if you passcubePositions
to another function, because then the array will decay to a pointer and will "loose" it's sizeof.However - this is not the recomended way to do it in C++.
It is better to use
std::vector
for a dynamic size array.It has a method:
size()
to retrieve the number of elements:Note: if your array has a fixed size (known at compile time), you can also use
std::array
. It also has asize()
method, although in this case it is not as useful, as the size cannot change dynamically and is actually one of the template parameters.Update::
As @HolyBlackCat commented below, it is better to use
std::size
to get the number of elements in an old C array:It will not compile if you pass a decayed pointer rather than a real array. Just keep in mind that as I wrote above you'd better avoid old C arrays if you can.