![](/img/trans.png)
[英]How do I check whether an index of array is empty and then, if it is, skip to the next?
[英]How to check whether an index in an array is empty
我正在为Uni的C ++类简介编写一个小型OpenGL程序。 我有一个完整的程序,但我想对其进行一些更改以使其更加独特。 我有一个Cube课程:
class Cube {
public:
Cube(Mesh* mesh, Texture2D* texture, float x, float y, float z);
~Cube();
void Draw();
void Update(float rSpeed);
Vector3 position;
private:
GLfloat rotationSpeed;
Vector3 rotationVector;
Mesh* _mesh;
Texture2D* _texture;
};
然后,我创建一个类型为Cube的数组:
Cube* cubes[CUBE_AMOUNT];
然后,我用数据填充此数组的每个索引,以便稍后在程序中在屏幕上绘制多维数据集:
for (int i = 0; i < CUBE_AMOUNT; i++) {
float x = ((rand() % 400) / 10.0f) - 20.0f;
float y = ((rand() % 200) / 10.0f) - 10.0f;
float z = -(rand() % 1000);
if (i % 2 == 1) {
cubes[i] = new Cube(cubeMesh, textureStars, x, y, z);
}
else {
cubes[i] = new Cube(cubeMesh, texturePenguins, x, y, z);
}
}
有了这个要添加到程序中的新东西,我想检查是否已经用数据填充了cubes []的索引。 但是,我在运行时不断收到异常。 我尝试检查cubes [i]是否等于nullptr,并尝试检查它是否也为NULL,但似乎都不匹配。
对不起,我使用的术语有误。 C ++的新手,并且之前只做过Python,这令人困惑!
解:
创建数组时,将其更改为Cube* cubes[CUBE_AMOUNT] = { NULL }
,现在检查数组时, cubes[i] == NULL
!
如果cubes
不是全局变量,则可以使用:
Cube* cubes[CUBE_AMOUNT] = {};
将所有元素初始化为nullptr
。
您还可以使用:
std::vector<std::unique_ptr<Cube>> cubes(CUBE_AMOUNT);
消除了必须在代码中重新分配动态内存的负担。
无论哪种情况,都可以使用:
if ( cubes[index] )
{
// Got a valid pointer. Use it.
}
您的cubes
变量不会自动使用null_ptr初始化。 直到您用null_ptr或好的指针填充它之前,它最初都指向随机垃圾。
我认为这会工作
//This bit should check if theres anything stored currently.
cout << "\nWhich Slot would you like to store the informaton in ?(1-10)";
cin >> i;
i--;
if (information[i] != NULL){
// Already written
cout << "THERES SOMETHING HERE";
}
else{
cout << "\nEMPTY!!!!!!!!!";
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.