假设我有很多布尔变量(我试图制作基于文本的冒险游戏,我将根据所选择的选择需要分离的路径),是否有一种简单的方法来检查给定的字符串是否相等到初始化变量的名称或初始化结构的成员? (这样我可以将变量从false更改为true,例如?)
答案 0 :(得分:0)
使用std::map
对抗怪物的快速示例。
protocol Observable {
typealias T : Equatable
var observers:[T] { get set }
mutating func removeObserver(observer:T)
}
extension Observable {
mutating func removeObserver(observer:T) {
if let index = self.observers.indexOf(observer) {
self.observers.removeAtIndex(index)
}
}
}
定义并分配一些命名标志列表,这些标志可能是也可能不是。可以使用此列表
std::map<std::string, bool> flags;
查看if (flags["key"])
以查看是否存在“密钥”。如果是,则返回映射值(flags
或true
)。如果它不存在,如果您熟悉Java,这是一个主要区别,则会创建“key”并将其设置为默认值(在这种情况下为false
)。
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);
}