sortkeys.cpp 1.6 KB

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