如何在Qt中为字符串编写switch语句

How to write a switch statement for strings in Qt?

本文关键字:switch 语句 字符串 Qt      更新时间:2023-10-16

我需要为与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项目文件的方法。

重要注意事项:

  1. 如果您关心与其他一些字符串的哈希冲突,则需要比较大小写中的字符串。不过,这仍然比进行 (N/2) 字符串比较便宜。

  2. qHash针对 QT 5 进行了重新设计,哈希与 Qt 4 不同。

  3. 不要忘记交换机中的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语句中使用枚举值