C ++如何使用较少的条件语句? [英] C++ How to use less conditional statements?
本文介绍了C ++如何使用较少的条件语句?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
对于我的任务,我要存储用户登录信息。我输入的是命令字符串。可以创建,登录,删除等命令。共有10个选项,即可以使用10个不同的字符串。谁能解释一种更有效的写方法,而不是10 if和else if语句?基本上,除了使用一堆 if(string == one)
, else if(string == two )
。谢谢
For my assignment, I'm storing user login infos. I'm taking in a string which is the command. The command can be create, login, remove, etc. There are 10 total options, i.e 10 different strings possible. Can anyone explain a more efficient way to write this instead of 10 if and else if statements? Basically how should I format/structure things besides using a bunch of if (string == "one")
, else if (string == "two")
. Thank you
推荐答案
您可以使用地图为您进行比较。
You can use a map which does the comparison for you.
类似这样的东西:
初始化地图:
std::map<std::string, std::function<void(std::string&)>> map;
map["login"] = std::bind(&Class::DoLogin, this, std::placeholders::_1);
map["create"] = std::bind(&Class::DoCreate, this, std::placeholders::_1);
接收消息:
map.at(rx.msg_type)(rx.msg_data);
处理程序:
void Class::DoLogin(const std::string& data)
{
// do login
}
这篇关于C ++如何使用较少的条件语句?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文