How to write a switch statement for strings in Qt?

风流意气都作罢 提交于 2019-12-30 10:50:53

问题


I need to create the equivalent of a switch/case statement for strings in C++ with Qt. I believe that the simplest way is something like this (pseudo code)

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";
}

But this doesn't take advantage of some of the features of Qt. I've read about QStringList's (to find the position of the string in a list of strings), and std:map (see How to easily map c++ enums to strings which I don't fully understand).

Is there a better way to do a switch on strings?


回答1:


The only way to use switch() with strings is to use an integer-valued hash of a string. You'll need to precompute hashes of the strings you're comparing against. This is the approach taken within qmake for reading visual studio project files, for example.

Important Caveats:

  1. If you care about hash collisions with some other strings, then you'll need to compare the string within the case. This is still cheaper than doing (N/2) string comparisons, though.

  2. qHash was reworked for QT 5 and the hashes are different from Qt 4.

  3. Do not forget the break statement within your switch. Your example code missed that, and also had nonsensical switch value!

Your code would look like the following:

#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;
}



回答2:


QStringList menuitems;
menuitems << "about" << "history";

switch(menuitems.indexOf(QString menuId)){
case 0:
    MBAbout();
    break;
case 1:
    MBHistory();
    break;
}



回答3:


I found a suggestion on another site to use a QStringList of colors, use IndexOf() in the switch, and then use the enum value in the case statements



来源:https://stackoverflow.com/questions/19081562/how-to-write-a-switch-statement-for-strings-in-qt

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!