【问题标题】:JsonCpp how to std::sort a Json::Value that is an arrayJsonCpp 如何对作为数组的 Json::Value 进行 std::sort 排序
【发布时间】:2014-09-02 13:57:48
【问题描述】:

我想使用类似于 std::sort() 的方法对作为(dicts 的)数组的 Json::Value 进行排序,但是在尝试像这样创建自定义排序函数时出现错误:

bool sort_json_array(Json::Value a, Json::Value b)
{
    return a["some_double_member"].asDouble() > b["some_double_member"].asDouble();
}

我调用 std::sort 如下:

std::sort(json_array.begin(), json_array.end(), sort_json_array);

但这给出了一些我不明白的错误,都类似于:

no match for ‘operator-’ (operand types are ‘Json::ValueIterator’ and ‘int’)

如何对 Json 数组进行排序?

【问题讨论】:

  • Json::ValueIterator 不满足RandomAccessIterator 所需的std::sort 要求。
  • 哦,谢谢 Jarod42。那太糟糕了。我想接下来的选择是遍历 Json 数组,将所有元素放入一个新向量中,然后对向量进行 std::sort ... 除非有人有更好的主意,否则我会试试这个。
  • 顺便说一句,您的 sort_json_array 将通过 const ref 接受他们的论点。
  • 您可以在迭代时将它们推入一个新的排序数组(按顺序插入)...无需复制两次...
  • 啊是的 const ref 更好。本杰明,下次我会记住这一点,但就我的程序而言,排序只会在程序的生命周期内发生一次,所以我可以多复制一份,因为代码现在可以工作,而且数组很小。

标签: c++ json sorting jsoncpp


【解决方案1】:

我选择的解决方案是创建一个新的空向量,然后遍历 Json 数组,将每个元素插入到向量中。然后我使用上述问题中的 sort_json_array() 对向量进行 std::sort() 处理(除了我将其更改为采用 Jarod42 建议的 const 引用)。谢谢大家的帮助!

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-11-20
    • 2011-08-19
    • 1970-01-01
    • 1970-01-01
    • 2016-09-11
    • 2013-07-01
    • 1970-01-01
    相关资源
    最近更新 更多