如何根据 QJsonArray 的子级之一实现自定义排序?

我有基于此 JSON 的 QJsonArray 玩具:

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

但这会引发很多错误。

请您参考如下方法:

有一些问题需要修复。首先,这是我的解决方案和下面的一些解释:

解决方案

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 & 替换为 const QJsonValue &。然后在函数体中显式处理到 QJsonObject 类型的转换:v1.toObject()... 而不是 v1...

没有交换功能!

您遇到的错误之一是:

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

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


评论关闭
IT虾米网

微信公众号号:IT虾米 (左侧二维码扫一扫)欢迎添加!