[英]EXC_BAD_ACCESS when passing std::vector as a parameter to a function
I have a function called calculateMaxPoint() which goes through an array of vec3s to determine the maximum x, y and z values. 我有一个称为calculateMaxPoint()的函数,该函数通过一系列vec3来确定最大的x,y和z值。 It is used across my file multiple different time, so that it is able to go through many different arrays.
它在我的文件中多次使用,因此它可以通过许多不同的数组。
It doesn't work though. 虽然不行。 I get an EXC_BAD_ACCESS exception at runtime when the function is called.
调用该函数时,在运行时出现EXC_BAD_ACCESS异常。 I've tried making the parameter into a pointer, and more recently I've tried using the
const
declaration. 我尝试将参数设置为指针,最近,我尝试使用
const
声明。 Neither worked. 两者都不起作用。
glm::vec3 calculateMaxPoint(std::vector<glm::vec3> & points) {
float max[3] = {points[0].x, points[0].y, points[0].z};
for (int i = 0; i < points.size(); i++) {
if (points[i].x > max[0])
max[0] = points[i].x;
if (points[i].y > max[1])
max[1] = points[i].y;
if (points[i].z > max[2])
max[2] = points[i].z;
}
return glm::vec3(max[0], max[1], max[2]);
}
If any info is needed, let me know. 如果需要任何信息,请告诉我。
As far as I can judge from your code, the issue could arise if the vector points
that is passed as an argument is empty (contains no elements). 据我从您的代码判断,如果作为参数传递的向量
points
为空(不包含任何元素),则可能会出现问题。 In that case referencing the element with index zero that you are doing on the first line is invalid. 在这种情况下,在第一行中引用索引为零的元素无效。 What you should do is add a line that checks if the vector is empty and handle that scenario.
您应该做的是添加一行,检查向量是否为空并处理该情况。 The snippet below returns a vector with all zero values:
以下代码段返回一个全为零的向量:
if (points.size() == 0)
{
// In this example return a vector with 0 values
return glm::vec3(0, 0, 0);
}
You can modify this code as to your needs - return a vector with different values or possibly throw and exception. 您可以根据需要修改此代码-返回具有不同值的向量,或者可能返回throw和exception。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.