buildheap.cxx 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. #include <cstdio>
  2. #include <iostream>
  3. #include <string>
  4. #include <fstream>
  5. #include <sstream>
  6. #include "json.hpp"
  7. #include "priorityqueue.h"
  8. int main(int argc, char** argv) {
  9. // read JSON file and store in jsonObject
  10. std::ifstream file;
  11. file.open(argv[1]);
  12. nlohmann::json jsonObject;
  13. // Store the contents filename into jsonObject
  14. if (file.is_open()) {
  15. file >> jsonObject;
  16. }
  17. std::string heapOp; // heap operation to iterate
  18. std::string currOp; // operation name
  19. int key; // node key given for each operation
  20. int newKey; // node key given for each operation
  21. // obtain max heap size from JSON input file and initialize priorityqueue heap with this number
  22. int n = jsonObject["metadata"]["maxHeapSize"];
  23. int opInHeap = jsonObject["metadata"]["numOperations"];
  24. class PriorityQueue opHeap;
  25. opHeap.initiateHeap(n);
  26. // initialize vector *** may not be needed ***
  27. std::vector<int> A(n, 0);
  28. // need to iterate through each operation
  29. for (auto itr = jsonObject.begin(); itr != jsonObject.end(); ++itr) {
  30. heapOp = itr.key();
  31. if (heapOp != "metadata") {
  32. // get the operation name to be performed
  33. currOp = jsonObject[heapOp]["operation"];
  34. // perform correct operation gotten from JSON Op object
  35. if (currOp == "insert") {
  36. key = jsonObject[heapOp]["key"];
  37. opHeap.insert(key);
  38. } else if (currOp == "change") {
  39. key = jsonObject[heapOp]["key"];
  40. newKey = jsonObject[heapOp]["newKey"];
  41. opHeap.change(key, newKey);
  42. } else if (currOp == "removeMax") {
  43. opHeap.removeMax();
  44. } else if (currOp == "removeKey") {
  45. key = jsonObject[heapOp]["key"];
  46. opHeap.removeKey(key);
  47. }
  48. }
  49. }
  50. // print tree using JSON formatting
  51. opHeap.printJSONTree(n, opInHeap);
  52. // clean up memory
  53. file.close();
  54. opHeap.deleteHeap();
  55. return 0;
  56. }