【问题标题】:How to check for the existence of a variable or a member of a struct?如何检查变量或结构成员是否存在?
【发布时间】:2016-07-09 17:13:42
【问题描述】:

假设我有很多布尔变量(我正在尝试制作基于文本的冒险游戏,并且我需要根据所选选择来分歧的路径),有没有一种简单的方法来检查给定的字符串是否相等初始化变量的名称或初始化结构的成员? (例如,我可以将变量从 false 更改为 true 吗?)

【问题讨论】:

  • 不。一旦程序编译完成,所有那些漂亮的变量名都消失了,取而代之的是内存偏移量。
  • 也许您想在课堂上使用std::map<std::string, bool>
  • std::set<std::string>
  • 不,C++ 不能这样工作。如果你需要很多东西,你可以为这些东西创建一个collection,而不是为每个东西创建一个变量。如果需要按字符串查找,请使用可按字符串索引的集合,例如 std::map。
  • 抱歉,C++ 不提供运行时反射。幸运的是。

标签: c++ variables if-statement struct boolean


【解决方案1】:

使用std::map 与怪物战斗的简单示例。

std::map<std::string, bool> flags;

定义并分配一个命名标志的列表,这些标志可能为真,也可能不为真。这个列表可以用

if (flags["key"])

查看flags 以查看“key”是否存在。如果是,则将返回映射值(truefalse)。如果它不存在,并且如果您熟悉 Java,这是一个主要区别,则会创建“key”并将其设置为默认值(在这种情况下为false)。

#include <iostream>
#include <map>

void slaymonster(std::map<std::string, bool> & flags)
{
    //check if hero has sword of monster slaying
    if (flags["has sword of monster slaying"])
    { 
        flags["monster slain"] = true; // sets key "monster slain" to true so
                                       // hero can do stuff that requires
                                       // monster to have been slain
        std::cout << "Thou hast slain the monster!\n";
    }
    else
    {
        std::cout << "Thou hast been slain by the monster!\nInsert coin to continue.\n";
    }
}

int main()
{
    std::map<std::string, bool> flags;

    std::cout << "Try to slay monster before finding sword\n";
    slaymonster(flags);

    std::cout << "\nHero finds sword of monster slaying\n";
    flags["has sword of monster slaying"] = true;
    std::cout << "Try to slay monster after finding sword\n";
    slaymonster(flags);

    std::cout << "\nHero is mugged and loses sword of monster slaying\n";
    flags["has sword of monster slaying"] = false;
    std::cout << "Try to slay monster after losing sword\n";
    slaymonster(flags);
}

输出:

Try to slay monster before finding sword
Thou hast been slain by the monster!
Insert coin to continue.

Hero finds sword of monster slaying
Try to slay monster after finding sword
Thou hast slain the monster!

Hero is mugged and loses sword of monster slaying
Try to slay monster after losing sword
Thou hast been slain by the monster!
Insert coin to continue.

【讨论】:

  • 这太棒了!很好的解释和一个非常相关的例子!谢谢!
猜你喜欢
  • 2017-06-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-07-04
  • 2010-10-25
  • 2016-04-29
  • 2012-06-30
  • 1970-01-01
相关资源
最近更新 更多