buildheap.cxx 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  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. //nlohmann::json outputJSON; // output JSON file
  19. std::string currOp; // operation name
  20. int key; // node key given for each operation
  21. int newKey; // node key given for each operation
  22. // obtain max heap size from JSON input file and initialize priorityqueue heap with this number
  23. int n = jsonObject["metadata"]["maxHeapSize"];
  24. int opInHeap = jsonObject["metadata"]["numOperations"];
  25. class PriorityQueue opHeap;
  26. opHeap.initiateHeap(n);
  27. // initialize vector *** may not be needed ***
  28. std::vector<int> A(n, 0);
  29. // need to iterate through each operation
  30. for (auto itr = jsonObject.begin(); itr != jsonObject.end(); ++itr) {
  31. heapOp = itr.key();
  32. if (heapOp != "metadata") {
  33. // get the operation name to be performed
  34. currOp = jsonObject[heapOp]["operation"];
  35. // perform correct operation gotten from JSON Op object
  36. if (currOp == "insert") {
  37. key = jsonObject[heapOp]["key"];
  38. opHeap.insert(key);
  39. } else if (currOp == "change") {
  40. key = jsonObject[heapOp]["key"];
  41. newKey = jsonObject[heapOp]["newKey"];
  42. opHeap.change(key, newKey);
  43. } else if (currOp == "removeMax") {
  44. opHeap.removeMax();
  45. } else if (currOp == "removeKey") {
  46. key = jsonObject[heapOp]["key"];
  47. opHeap.removeKey(key);
  48. }
  49. }
  50. }
  51. // print tree using JSON formatting
  52. opHeap.printJSONTree(n, opInHeap);
  53. // clean up memory
  54. file.close();
  55. opHeap.deleteHeap();
  56. return 0;
  57. }