首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
社区首页 >问答首页 >如何在Qt中编写字符串的switch语句?

如何在Qt中编写字符串的switch语句?
EN

Stack Overflow用户
提问于 2013-09-30 02:16:37
回答 3查看 11.3K关注 0票数 3

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

代码语言:javascript
代码运行次数:0
运行
复制
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 )。

有没有更好的方法在字符串上进行切换?

EN

回答 3

Stack Overflow用户

回答已采纳

发布于 2013-09-30 03:43:15

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

重要注意事项:

  1. 如果你关心与其他字符串的哈希冲突,那么你需要在大小写中比较字符串。这仍然比做(N/2)字符串比较便宜,though.
  2. qHash是为QT 5重新编写的,并且散列与Qt 4不同。
  3. 不要忘记开关中的break语句。您的示例代码遗漏了这一点,并且还具有无意义的开关值!

您的代码将如下所示:

代码语言:javascript
代码运行次数:0
运行
复制
#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;
}
票数 4
EN

Stack Overflow用户

发布于 2016-12-07 09:47:00

代码语言:javascript
代码运行次数:0
运行
复制
QStringList menuitems;
menuitems << "about" << "history";

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

Stack Overflow用户

发布于 2013-10-01 00:58:51

我在另一个站点上发现了一个建议,建议使用颜色的QStringList,在开关中使用IndexOf(),然后在case语句中使用枚举值

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/19081562

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档