如何根据其子级之一对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();
});
但这会引发很多错误。
最佳答案
有几件事需要修复。首先,这是我的解决方案,下面是一些解释:
解
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
元素的实现。感谢错误报告者Keith Gardner,我们可以包括我们自己的交换功能。如报告中所建议,您可能希望将其作为内联函数放在全局头文件中。关于c++ - 通过其子元素之一对QJsonArray进行排序,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/54461719/