Skip to content

Commit

Permalink
Merge pull request #1421 from HomeControlAS/sort_by_name_example
Browse files Browse the repository at this point in the history
added example for sorting keys
  • Loading branch information
miloyip committed Feb 6, 2019
2 parents 79a6dab + d018846 commit 1892013
Show file tree
Hide file tree
Showing 2 changed files with 67 additions and 0 deletions.
1 change: 1 addition & 0 deletions example/CMakeLists.txt
Expand Up @@ -21,6 +21,7 @@ set(EXAMPLES
simplereader
simplepullreader
simplewriter
sortkeys
tutorial)

include_directories("../include/")
Expand Down
66 changes: 66 additions & 0 deletions example/sortkeys/sortkeys.cpp
@@ -0,0 +1,66 @@
#include "rapidjson/document.h"
#include "rapidjson/filewritestream.h"
#include <rapidjson/prettywriter.h>

#include <algorithm>
#include <iostream>

using namespace rapidjson;
using namespace std;

void printIt(const Value &doc)
{
char writeBuffer[65536];
FileWriteStream os(stdout, writeBuffer, sizeof(writeBuffer));
PrettyWriter<FileWriteStream> writer(os);
doc.Accept(writer);

cout << endl;
}

struct NameComparator
{
bool
operator()(const GenericMember<UTF8<>, MemoryPoolAllocator<>> &lhs,
const GenericMember<UTF8<>, MemoryPoolAllocator<>> &rhs) const
{
return (strcmp(lhs.name.GetString(), rhs.name.GetString()) < 0);
}
};

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(), NameComparator());

printIt(d);
/**
{
"alpha": [],
"delta": 123,
"gama": "test string",
"zeta": false
}
**/
return 0;
}

0 comments on commit 1892013

Please sign in to comment.