【问题标题】:Sort a QJsonArray by one of its child elements按其子元素之一对 QJsonArray 进行排序
【发布时间】:2019-06-24 23:32:55
【问题描述】:

如何根据其中一个子项对 QJsonArray 进行自定义排序?

我有基于此 JSON 的QJsonArray toys

"toys": [
    {
        "type": "teddy",
        "name": "Thomas",
        "size": 24
    },
    {
        "type": "giraffe",
        "name": "Jenny",
        "size": 28
    },
    {
        "type": "alligator",
        "name": "Alex",
        "size": 12
    }
]

我想按"name" 的字母顺序排序。

我试过了:

std::sort(toys.begin(), toys.end(), [](const QJsonObject &v1, const QJsonObject &v2) {
    return v1["name"].toString() < v2["name"].toString();
});

但这会引发很多错误。

【问题讨论】:

    标签: c++ json qt sorting


    【解决方案1】:

    有几件事需要解决。首先,这是我的解决方案,下面是一些解释:

    解决方案

    inline void swap(QJsonValueRef v1, QJsonValueRef v2)
    {
        QJsonValue temp(v1);
        v1 = QJsonValue(v2);
        v2 = temp;
    }
    
    std::sort(toys.begin(), toys.end(), [](const QJsonValue &v1, const QJsonValue &v2) {
        return v1.toObject()["name"].toString() < v2.toObject()["name"].toString();
    });
    

    说明

    比较参数

    您遇到的错误之一是:

    no matching function for call to object of type '(lambda at xxxxxxxx)'
            if (__comp(*--__last, *__first))
                ^~~~~~
    
    ...
    
    candidate function not viable: no known conversion from 'QJsonValueRef' to 'const QJsonObject' for 1st argument
    std::sort(toys.begin(), toys.end(), [](const QJsonObject &v1, const QJsonObject &v2) {
                                        ^
    ...
    

    迭代器不知道您的数组元素是QJsonObject 类型。相反,它将它们视为通用的 QJsonValue 类型。不会自动转换为 QJsonObject,因此它会在您的 lambda 函数中引发错误。

    将两个 lambda 参数的 const QJsonObject &amp; 替换为 const QJsonValue &amp;。然后在函数体中显式处理转换为QJsonObject 类型:v1.toObject()... 而不是v1...

    没有交换功能!

    您遇到的错误之一是:

    no matching function for call to 'swap'
                swap(*__first, *__last);
                ^~~~
    

    正如 Qt 错误报告 QTBUG-44944 中所讨论的,Qt 没有提供交换数组中两个 QJsonValue 元素的实现。感谢错误报告者 Keith Gardner,我们可以包含我们自己的交换功能。正如报告中所建议的,您可能希望将其作为内联函数放在全局头文件中。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-12-26
      • 2019-09-01
      • 1970-01-01
      • 2021-08-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多