fork download
  1. #include <iostream>
  2. #include <string>
  3. #include <cstring> //std::memcpy
  4.  
  5. class CustomClass
  6. {
  7. private:
  8. std::string a;
  9. std::string b;
  10. public:
  11. CustomClass(std::string a, std::string b): a(a), b(b) {}
  12. std::string to_string()
  13. {
  14. return a + " of " + b;
  15. }
  16. };
  17.  
  18. class CustomArray
  19. {
  20. private:
  21.  
  22. CustomClass **arr = nullptr;
  23. size_t capacity = 0;
  24. size_t size = 0;
  25.  
  26.  
  27. public:
  28.  
  29. void resize(size_t new_capacity)
  30. {
  31. CustomClass** resized_arr = new CustomClass*[new_capacity]();
  32. std::memcpy(resized_arr, arr, capacity * sizeof(CustomClass*));
  33.  
  34. delete[] arr;
  35.  
  36. capacity = new_capacity;
  37. arr = resized_arr;
  38.  
  39. }
  40. void add(CustomClass* cc)
  41. {
  42. if (size <= capacity)
  43. this->resize(capacity + 1);
  44.  
  45. arr[size++] = cc;
  46. }
  47.  
  48. void print()
  49. {
  50. for (size_t i = 0; i < capacity; i++)
  51. {
  52. if (arr[i] == nullptr)
  53. std::cout << "KEY: " << i << ", VAL: NULL" << std::endl;
  54. else
  55. std::cout << "KEY: " << i << ", VAL: " << arr[i]->to_string() << std::endl;
  56. }
  57.  
  58. std::cout << std::endl;
  59. }
  60. };
  61.  
  62.  
  63.  
  64. int main()
  65. {
  66. CustomArray arr;
  67. arr.print(); // nothing
  68.  
  69. CustomClass cc1("1", "3");
  70. arr.add(&cc1);
  71. CustomClass cc2("2", "3");
  72. arr.add(&cc2);
  73. CustomClass cc3("3", "3");
  74. arr.add(&cc3);
  75. arr.print(); // prints 3 elements
  76.  
  77. arr.resize(5);
  78. arr.print(); //prints 2 nore NULLs
  79.  
  80.  
  81. return 0;
  82. }
Success #stdin #stdout 0s 16064KB
stdin
Standard input is empty
stdout
KEY: 0, VAL: 1 of 3
KEY: 1, VAL: 2 of 3
KEY: 2, VAL: 3 of 3

KEY: 0, VAL: 1 of 3
KEY: 1, VAL: 2 of 3
KEY: 2, VAL: 3 of 3
KEY: 3, VAL: NULL
KEY: 4, VAL: NULL