Debian Codegraph @

LspCpp/third_party/rapidjson/example/sortkeys/sortkeys.cpp

raw
1 #include "rapidjson/document.h"
2 #include "rapidjson/filewritestream.h"
3 #include <rapidjson/prettywriter.h>
4
5 #include <algorithm>
6 #include <iostream>
7
8 using namespace rapidjson;
9 using namespace std;
10
11 static void printIt(const Value &doc) {
12 char writeBuffer[65536];
13 FileWriteStream os(stdout, writeBuffer, sizeof(writeBuffer));
14 PrettyWriter<FileWriteStream> writer(os);
15 doc.Accept(writer);
16 cout << endl;
17 }
18
19 struct NameComparator {
20 bool operator()(const Value::Member &lhs, const Value::Member &rhs) const {
21 return (strcmp(lhs.name.GetString(), rhs.name.GetString()) < 0);
22 }
23 };
24
25 int main() {
26 Document d(kObjectType);
27 Document::AllocatorType &allocator = d.GetAllocator();
28
29 d.AddMember("zeta", Value().SetBool(false), allocator);
30 d.AddMember("gama", Value().SetString("test string", allocator), allocator);
31 d.AddMember("delta", Value().SetInt(123), allocator);
32 d.AddMember("alpha", Value(kArrayType).Move(), allocator);
33
34 printIt(d);
35
36 /*
37 {
38 "zeta": false,
39 "gama": "test string",
40 "delta": 123,
41 "alpha": []
42 }
43 */
44
45 // C++11 supports std::move() of Value so it always have no problem for std::sort().
46 // Some C++03 implementations of std::sort() requires copy constructor which causes compilation error.
47 // Needs a sorting function only depends on std::swap() instead.
48 #if __cplusplus >= 201103L || (!defined(__GLIBCXX__) && (!defined(_MSC_VER) || _MSC_VER >= 1900))
49 std::sort(d.MemberBegin(), d.MemberEnd(), NameComparator());
50
51 printIt(d);
52
53 /*
54 {
55 "alpha": [],
56 "delta": 123,
57 "gama": "test string",
58 "zeta": false
59 }
60 */
61 #endif
62 }