fork(1) download
  1. #include <cstdint>
  2. #include <new>
  3.  
  4. template <typename T>
  5. struct buffer_allocator
  6. {
  7. using size_type = std::size_t;
  8. using difference_type = std::ptrdiff_t;
  9. using pointer = T*;
  10. using const_pointer = const T*;
  11. using reference = T&;
  12. using const_reference = const T&;
  13. using value_type = T;
  14.  
  15. buffer_allocator(T* buffer, std::size_t max_size) :
  16. buffer(buffer), max_size(max_size)
  17. {}
  18.  
  19. template<typename... Args>
  20. void construct(T* p, Args&&... args)
  21. { /*::new((void *)p) T(std::forward<Args>(args)...);*/ }
  22.  
  23. void destroy(T* p) { /*p->~T();*/ }
  24.  
  25. T* allocate(std::size_t n)
  26. {
  27. if (max_size != n) { throw std::bad_alloc{}; }
  28. return buffer;
  29. }
  30.  
  31. void deallocate(T*, std::size_t) {}
  32.  
  33. std::size_t get_max_size() const { return max_size; }
  34.  
  35. private:
  36. T* buffer;
  37. std::size_t max_size;
  38. };
  39.  
  40. #include <iostream>
  41. #include <vector>
  42.  
  43. int main()
  44. {
  45. std::vector<int> v{0, 1, 2, 3, 4};
  46. buffer_allocator<int> b1(v.data(), 3);
  47. buffer_allocator<int> b2(v.data() + 3, v.size() - 3);
  48. std::vector<int, buffer_allocator<int>> v1(b1.get_max_size(), b1);
  49. std::vector<int, buffer_allocator<int>> v2(b2.get_max_size(), b2);
  50.  
  51. std::cout << "v1 =";
  52. for (auto e : v1) {
  53. std::cout << " " << e;
  54. }
  55. std::cout << std::endl << "v2 =";
  56. for (auto e : v2) {
  57. std::cout << " " << e;
  58. }
  59. return 0;
  60. }
  61.  
Success #stdin #stdout 0s 3472KB
stdin
Standard input is empty
stdout
v1 = 0 1 2
v2 = 3 4