Skip to content

Commit 1892013

Browse files
authored
Merge pull request Tencent#1421 from HomeControlAS/sort_by_name_example
added example for sorting keys
2 parents 79a6dab + d018846 commit 1892013

File tree

2 files changed

+67
-0
lines changed

2 files changed

+67
-0
lines changed

example/CMakeLists.txt

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -21,6 +21,7 @@ set(EXAMPLES
2121
simplereader
2222
simplepullreader
2323
simplewriter
24+
sortkeys
2425
tutorial)
2526

2627
include_directories("../include/")

example/sortkeys/sortkeys.cpp

Lines changed: 66 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,66 @@
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+
void printIt(const Value &doc)
12+
{
13+
char writeBuffer[65536];
14+
FileWriteStream os(stdout, writeBuffer, sizeof(writeBuffer));
15+
PrettyWriter<FileWriteStream> writer(os);
16+
doc.Accept(writer);
17+
18+
cout << endl;
19+
}
20+
21+
struct NameComparator
22+
{
23+
bool
24+
operator()(const GenericMember<UTF8<>, MemoryPoolAllocator<>> &lhs,
25+
const GenericMember<UTF8<>, MemoryPoolAllocator<>> &rhs) const
26+
{
27+
return (strcmp(lhs.name.GetString(), rhs.name.GetString()) < 0);
28+
}
29+
};
30+
31+
int main()
32+
{
33+
Document d = Document(kObjectType);
34+
Document::AllocatorType &allocator = d.GetAllocator();
35+
36+
d.AddMember("zeta", Value().SetBool(false), allocator);
37+
d.AddMember("gama", Value().SetString("test string", allocator), allocator);
38+
d.AddMember("delta", Value().SetInt(123), allocator);
39+
40+
Value a(kArrayType);
41+
d.AddMember("alpha", a, allocator);
42+
43+
printIt(d);
44+
45+
/**
46+
{
47+
"zeta": false,
48+
"gama": "test string",
49+
"delta": 123,
50+
"alpha": []
51+
}
52+
**/
53+
54+
std::sort(d.MemberBegin(), d.MemberEnd(), NameComparator());
55+
56+
printIt(d);
57+
/**
58+
{
59+
"alpha": [],
60+
"delta": 123,
61+
"gama": "test string",
62+
"zeta": false
63+
}
64+
**/
65+
return 0;
66+
}

0 commit comments

Comments
 (0)