如何检查数组中的索引是否为空 我正在为乌尼的C++类做一个小OpenGL程序。我有一个完整的程序,但我想把它修改一点,使它更独特。我有一个立方体类: 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; };

如何检查数组中的索引是否为空 我正在为乌尼的C++类做一个小OpenGL程序。我有一个完整的程序,但我想把它修改一点,使它更独特。我有一个立方体类: 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; };,c++,C++,然后,我创建一个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

然后,我创建一个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);
    }
}
for(int i=0;i
有了这个我想添加到程序中的新东西,我想检查cubes[]的索引是否已经填充了数据。但是,我在运行时不断遇到异常。我试着检查cubes[I]是否等于nullptr,也试着检查它是否为NULL,但两者似乎都不匹配

对不起,我使用的术语有任何错误。新的C++,并且来自于在这之前只做Python,它很混乱!p> 解决方案:


创建数组时,我将其更改为
Cube*cubes[Cube\u AMOUNT]={NULL}
,现在检查数组时,
cubes[I]==NULL

您的
多维数据集
变量不会自动初始化为空值。除非您用空指针或好指针填充它,否则它最初指向随机垃圾。

如果
多维数据集
不是全局变量,您可以使用:

Cube* cubes[CUBE_AMOUNT] = {};
将所有元素初始化为
nullptr

您还可以使用:

std::vector<std::unique_ptr<Cube>> cubes(CUBE_AMOUNT);

我想这会管用的

    //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!!!!!!!!!";
       }
//此位应检查当前是否存储了任何内容。
cout>i;
我--;
如果(信息[i]!=NULL){
//已经写好

cout“我试图检查多维数据集[I]是否等于NULL ptr,并尝试检查它是否为NULL,但两者似乎都不匹配。”-您能提供一个此代码的示例吗?好的,我编辑了底部的原始Q。多维数据集*多维数据集[Cube_AMOUNT]={0}C++对数组内容不进行初始化。如果你想指针为空,你需要用<代码>初始化它们(int i=0;IGOT,谢谢!我做了代码>立方体*立方体[CuByIOFAUT] = {NUL}} /代码>
    //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!!!!!!!!!";
       }