如何在Qt中为字符串编写switch语句
How to write a switch statement for strings in Qt?
我需要为与Qt C++中的字符串创建等效的switch/case语句。我相信最简单的方法是这样的(伪代码)
enum colours { red, green, blue };
QString array[] colour_names = { "red", "green", "blue" };
switch (color_names[user_string]) {
case red: answer="Chose red";
case green: answer="Chose green";
case blue: answer="Chose blue";
other: answer="Invalid choice";
}
但这并没有利用Qt的一些功能。 我已经阅读了QStringList(在字符串列表中找到字符串的位置)和std:map(请参阅如何轻松地将c ++枚举映射到我不完全理解的字符串)。
有没有更好的方法来切换字符串?
将switch()
与字符串一起使用的唯一方法是使用字符串的整数值哈希。您需要预先计算要与之比较的字符串的哈希值。例如,这是qmake中用于读取Visual Studio项目文件的方法。
重要注意事项:
-
如果您关心与其他一些字符串的哈希冲突,则需要比较大小写中的字符串。不过,这仍然比进行 (N/2) 字符串比较便宜。
-
qHash
针对 QT 5 进行了重新设计,哈希与 Qt 4 不同。 -
不要忘记交换机中的
break
语句。您的示例代码错过了这一点,并且还具有无意义的开关值!
您的代码如下所示:
#include <cstdio>
#include <QTextStream>
int main(int, char **)
{
#if QT_VERSION < QT_VERSION_CHECK(5,0,0)
static const uint red_hash = 30900;
static const uint green_hash = 7244734;
static const uint blue_hash = 431029;
#else
static const uint red_hash = 112785;
static const uint green_hash = 98619139;
static const uint blue_hash = 3027034;
#endif
QTextStream in(stdin), out(stdout);
out << "Enter color: " << flush;
const QString color = in.readLine();
out << "Hash=" << qHash(color) << endl;
QString answer;
switch (qHash(color)) {
case red_hash:
answer="Chose red";
break;
case green_hash:
answer="Chose green";
break;
case blue_hash:
answer="Chose blue";
break;
default:
answer="Chose something else";
break;
}
out << answer << endl;
}
QStringList menuitems;
menuitems << "about" << "history";
switch(menuitems.indexOf(QString menuId)){
case 0:
MBAbout();
break;
case 1:
MBHistory();
break;
}
我在另一个网站上发现了一个建议,即使用QString列表的颜色,在开关中使用IndexOf(),然后在case语句中使用枚举值
相关文章:
- 当调用switch语句中的函数时(即使函数不包含循环),似乎是永不结束的循环的问题
- 如何将 if else 语句重写为 switch 语句
- Switch 语句(字符串)一直选择默认值,除非其为零
- C++ switch 语句:对案例进行分组,并针对每个案例给出特定的说明
- 任意大小的 constexpr 数组是否可以用作 switch 语句中的案例?
- 默认标签显然在 switch 语句中不起作用
- C++如何在 switch 语句中放置两个参数
- 如何在 c++ 中从 switch 语句返回不同类型的变量
- 在编译时自动生成用于稀疏数组索引的switch语句
- C++ Switch 语句中的数学运算
- 变量不能在 lambda 中隐式捕获,并且没有使用 switch 语句指定捕获默认值
- 在任何案例之前,在 switch 语句中的使用声明是否合法?
- 使用 switch 语句将不同的函数作为类属性分配 C++
- 为什么我的 switch 语句没有响应一半的情况?
- 如何从映射中获取值并在 C++ 的 switch 语句中使用它
- switch 语句导致发送两条消息
- C++ Switch 语句在中断后执行
- switch语句,两种类似情况不同
- switch 语句和对象隐式 int 转换
- switch 语句结束和下一条语句之间的时间是否具有确定性(与路径无关)