我需要用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 (请参阅我不完全理解的How to easily map c++ enums to strings )。
有没有更好的方法在字符串上进行切换?
发布于 2013-09-30 03:43:15
对字符串使用switch()
的唯一方法是使用字符串的整数值散列。您需要预先计算要比较的字符串的散列。例如,这是在qmake中用于读取visual studio项目文件的方法。
重要注意事项:
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;
}
发布于 2016-12-07 09:47:00
QStringList menuitems;
menuitems << "about" << "history";
switch(menuitems.indexOf(QString menuId)){
case 0:
MBAbout();
break;
case 1:
MBHistory();
break;
}
发布于 2013-10-01 00:58:51
我在另一个站点上发现了一个建议,建议使用颜色的QStringList,在开关中使用IndexOf(),然后在case语句中使用枚举值
https://stackoverflow.com/questions/19081562
复制相似问题