简体   繁体   English

C-检查结构数组的所有值是否返回相同的值

[英]C - Check If All Values of Struct Array Return Same Values

I want to check if all values of a struct array hold the same value for the purpose of hiding "deleted" entries in the struct array. 我想检查结构数组的所有值是否都具有相同的值,以便在结构数组中隐藏“已删除”条目。

My struct looks like this: 我的结构看起来像这样:

struct spawnedObject {
    Hash objHash;
    Object obj;
    char* displayname;

    int invisibility;
    Vector3 position;

    int deleted; // 1=deleted and hidden, 0=should be listed and available
};

And I want to check if deleted is true for all entries in the struct. 而且我想检查结构中的所有条目的deleted是否为true。 When they're all true, have the else display the empty text. 当它们全部成立时,让else显示空白文本。

I have tried looping all deleted values and increasing an int when a value is set to 1 like so: 我试过循环所有deleted值,并在将值设置为1时增加一个整数,如下所示:

void objectManagerMenu() {
    objectVar = 0;
    int inc = 0; //store deleted entries count

    // loop through all entries. if entry deleted, increase.
    for (int i = 0; i < objectCount; i++) {
        if(spawnedObjects[i].deleted) inc++;
    }

    // check if there either are no entries, or if theyre hidden. if all stored entries are hidden, fallback to else. this is where it goes wrong.
    // problem: does not seem to fallback to else.
    if(objectCount != 0 || objectCount != inc) {
        for (int i = 0; i < objectCount; i++) {
            if(!spawnedObjects[i].deleted) { // remove hidden items from list
                char buffer[150];
                sprintf(buffer, "[ %i ] %s", i, spawnedObjects[i].displayname);

                menu.option(buffer).call(objectItemVar, i).submenu(objectItemMenu);
            }
        }
    } else {
        menu.option("Empty");
    }
}

Doesn't seem to work as nothing is being displayed. 由于没有显示任何内容,因此似乎无法正常工作。

Does anybody have a suggestion how I can do this a smarter way? 有人建议我如何更聪明地做到这一点吗?

The problem is your || 问题是您的|| in the if statement like stated int the comment. 在if语句中,例如int注释。

objectCount != 0

most likely returns true 最有可能返回true

objectCount != inc

returns false, because the menu is empty (in your current scenario which you are tryining to test) 返回false,因为菜单为空(在您尝试测试的当前方案中)
by that the if statement will always be true (if your object count is bigger then 0) and thus else is never executed. 这样, if语句将始终为true(如果您的对象计数大于0),因此永远不会执行else change the || 更改|| to && &&

Why 为什么
|| returns true if at least one of the statements gives true. 如果至少其中一个语句为true,则返回true。
&& returns true only when both are true and that is what you want && 仅当两个都为真时才返回true

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM