fork download
  1. #include <iostream>
  2. #include <memory>
  3.  
  4. // using namespace std;
  5.  
  6. // 15. Define a pvector to be like a vector of pointers except that it contains pointers to objects and its destructor
  7. // deletes each object.
  8.  
  9. template<typename T, typename A = std::allocator<T>> // T has to be a pointer
  10. class pvector
  11. {
  12. private:
  13. A alloc;
  14. int sz;
  15. T* elem;
  16. int space;
  17. public:
  18. pvector() : sz{0}, elem{nullptr}, space{0} { }
  19.  
  20. void resize(int newsize, T def = T());
  21. void push_back(const T val);
  22. void reserve(int newalloc);
  23.  
  24. T& operator[ ](int n) { return elem[n]; } // access: return reference
  25. const T& operator[](int n) const { return elem[n]; }
  26.  
  27. int size() { return sz; }
  28. };
  29.  
  30. template<typename T, typename A>
  31. void pvector<T,A>::reserve(int newalloc)
  32. {
  33. if (newalloc<=space) return; // never decrease allocation
  34. T* p = alloc.allocate(newalloc); // allocate new space
  35. for (int i=0; i<sz; ++i) alloc.construct(&p[i],elem[i]); // copy
  36. for (int i=0; i<sz; ++i) alloc.destroy(&elem[i]); // destroy
  37. alloc.deallocate(elem,space); // deallocate old space
  38. elem = p;
  39. space = newalloc;
  40. }
  41.  
  42. template<typename T, typename A>
  43. void pvector<T,A>::resize(int newsize, T val)
  44. {
  45. reserve(newsize);
  46. for (int i=sz; i<newsize; ++i) alloc.construct(&elem[i],val); // construct
  47. for (int i = newsize; i<sz; ++i) alloc.destroy(&elem[i]); // destroy
  48. sz = newsize;
  49. }
  50.  
  51. template<typename T, typename A>
  52. void pvector<T, A>::push_back(const T val)
  53. {
  54. if (space==0) reserve(8); // start with space for 8 elements
  55. else if (sz==space) reserve(2*space); // get more space
  56. T* n = new T;
  57. *n = val;
  58. intptr_t address = &n;
  59. alloc.construct(&elem[sz], address); // add val at end
  60.  
  61. // elem should be an array of pointers... construct expects a value
  62. // how to pass a pointer as an argument to construct() ?
  63.  
  64. ++sz;
  65. }
  66.  
  67. int main()
  68. {
  69. pvector<int> p;
  70. p.push_back(3);
  71.  
  72. return 0;
  73. }
  74.  
Compilation error #stdin compilation error #stdout 0s 0KB
stdin
Standard input is empty
compilation info
prog.cpp: In instantiation of ‘void pvector<T, A>::push_back(T) [with T = int; A = std::allocator<int>]’:
prog.cpp:70:18:   required from here
prog.cpp:58:25: error: invalid conversion from ‘int**’ to ‘intptr_t {aka long int}’ [-fpermissive]
     intptr_t address = &n;
                         ^
stdout
Standard output is empty