如何有效地识别字符串命令? [英] How to efficiently identify string commands?
问题描述
给出一系列必须针对每个命令运行的命令和非常独特的代码:
Given a series of commands and very unique code that must be run for each:
if(cmd == "cmd.setBoosterRocket")
...
else if(cmd == "cmd.windSales")
...
else if(cmd == "cmd.selfDustruct")
...
else if(cmd == "cmd.unleashHounds")
...
如何优化?放在switch语句中,是吗?
How might this be optimized? Be put into a switch statement, that is?
我考虑过制作哈希向量:
I considered making a vector of hashes:
std::hash<std::string> hasher;
for(std::string command : m_commandList)
m_mashes.push_back(hasher(command)
但是向量不能作为switch case语句的一部分进行访问,因为它不是constexpr.字符串命令列表在编译时就已知道,我可能会对哈希值进行硬编码...但这似乎不是一个好主意.
But a vector cannot be accessed as part of a switch case statement as it is not a constexpr. The list of string commands is known at compile time, and I could potentially hardcode the hash values...but that does not seem like a great idea.
推荐答案
一种可能的方法是标记化:创建 enum
类型和字典.这样一来,您可以利用切换功能(与硬编码的散列相比,对程序员和编译器更友好),并且具有对数复杂性.
One possible approach is tokenization: make an enum
type and a dictionary. This way you take advantage of the switch (in a more programmer and compiler friendly way than hard-coded hashes) and have just logarithmic complexity.
enum Command {SET_BOOSTER_ROCKET, WINDSALES, ETC};
const std::map<std::string, Command> commands = {
{"cmd.setBoosterRocket", SET_BOOSTER_ROCKET},
{"cmd.windsales", WINDSALES},
{"othercommands", ETC},
};
然后
auto cmd_it = commands.find(cmd);
if(cmd_it == commands.end()) { // ERROR }
switch(cmd_it->second){
case SET_BOOSTER_ROCKET:
// your code
break;
case WINDSALES:
// your code
break;
// etc
}
像这样的标记化如果您需要大量的操作,您的命令可能会有些乏味,但是在可伸缩性和可读性之间要有一个很好的平衡.
Tokenizing like this your commands might be a little tedious if you have a lot to start, but then it has a good balance between scalability and readability.
这篇关于如何有效地识别字符串命令?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!