如何为Qt中的字符串编写switch语句? [英] How to write a switch statement for strings in Qt?

查看:2494
本文介绍了如何为Qt中的字符串编写switch语句?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要使用Qt为C ++中的字符串创建等效的switch / case语句。我相信最简单的方法是这样的(伪代码)

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

但是这并没有利用Qt的一些功能。我已经阅读了关于QStringList(找到字符串在字符串列表中的位置)和std:map(参见如何轻松地将c ++枚举映射到字符串(我不完全明白)。

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).

有没有

推荐答案

使用 switch()使用字符串是使用字符串的整数值散列。您需要预先计算要比较的字符串的哈希值。例如,这是在qmake中用于阅读visual studio项目文件的方法。

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.

重要提醒:


  1. 如果您关心与一些其他的字符串,那么你需要比较的情况下的字符串。但是,这比N / 2的字符串比较还要便宜。

  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.

qHash 对于QT 5,散列与Qt 4不同。

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

不要忘记 break 你的开关您的示例代码错过了,并且还具有无意义的切换值!

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

您的代码如下所示: p>

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

这篇关于如何为Qt中的字符串编写switch语句?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆