From c9060b4a5c29a0d9fc69573695e600add61b75fc Mon Sep 17 00:00:00 2001 From: seky Date: Tue, 4 Dec 2018 22:40:40 +0100 Subject: [PATCH] added example for sorting keys --- example/CMakeLists.txt | 1 + example/sortkeys/sortkeys.cpp | 70 +++++++++++++++++++++++++++++++++++ 2 files changed, 71 insertions(+) create mode 100644 example/sortkeys/sortkeys.cpp diff --git a/example/CMakeLists.txt b/example/CMakeLists.txt index ff54199..9f53c9a 100644 --- a/example/CMakeLists.txt +++ b/example/CMakeLists.txt @@ -21,6 +21,7 @@ set(EXAMPLES simplereader simplepullreader simplewriter + sortkeys tutorial) include_directories("../include/") diff --git a/example/sortkeys/sortkeys.cpp b/example/sortkeys/sortkeys.cpp new file mode 100644 index 0000000..fb45d4a --- /dev/null +++ b/example/sortkeys/sortkeys.cpp @@ -0,0 +1,70 @@ +#define RAPIDJSON_HAS_STDSTRING 1 +#include "rapidjson/document.h" +#include +#include + +#include +#include + +using namespace rapidjson; +using namespace std; + +void printIt(Document &doc) +{ + string output; + StringBuffer buffer; + PrettyWriter writer(buffer); + doc.Accept(writer); + + output = buffer.GetString(); + cout << output << endl; +} + +struct ValueNameComparator +{ + bool + operator()(const GenericMember, MemoryPoolAllocator<>> &lhs, + const GenericMember, MemoryPoolAllocator<>> &rhs) const + { + string lhss = string(lhs.name.GetString()); + string rhss = string(rhs.name.GetString()); + return lhss < rhss; + } +}; + +int main() +{ + Document d = Document(kObjectType); + Document::AllocatorType &allocator = d.GetAllocator(); + + d.AddMember("zeta", Value().SetBool(false), allocator); + d.AddMember("gama", Value().SetString("test string", allocator), allocator); + d.AddMember("delta", Value().SetInt(123), allocator); + + Value a(kArrayType); + d.AddMember("alpha", a, allocator); + + printIt(d); + + /** +{ + "zeta": false, + "gama": "test string", + "delta": 123, + "alpha": [] +} +**/ + + std::sort(d.MemberBegin(), d.MemberEnd(), ValueNameComparator()); + + printIt(d); + /** +{ + "alpha": [], + "delta": 123, + "gama": "test string", + "zeta": false +} +**/ + return 0; +}