fork download
  1. #include <iostream>
  2. #include <cstddef>
  3. #include <new>
  4. #include <string.h>
  5.  
  6. template <typename T>
  7. struct infinite_array {
  8. infinite_array();
  9. auto operator[](unsigned long long idx) -> T&;
  10.  
  11. auto size() const -> unsigned long long;
  12. void resize(unsigned long long idx);
  13.  
  14. private:
  15. T *data;
  16. unsigned long long array_length;
  17. };
  18.  
  19. template <typename T>
  20. void infinite_array<T> :: resize(unsigned long long idx)
  21. {
  22. std::cout << "Resize with idx " << idx << std::endl;
  23. T *temp = new T[idx];
  24. memset(temp, 0, sizeof(T)*idx);
  25.  
  26. for(int i = 0; i < array_length; ++i) {
  27. temp[i] = data[i];
  28. std::cout << temp[i] << " ";
  29. }
  30. std::cout << std::endl;
  31. //std::copy(data, data+size(), temp);
  32. delete [] data;
  33.  
  34. data = temp;
  35. array_length = idx;
  36.  
  37. }
  38.  
  39. template <typename T>
  40. infinite_array<T> :: infinite_array()
  41. {
  42. data = NULL;
  43. array_length = 0;
  44. }
  45.  
  46. template <typename T>
  47. auto infinite_array<T> :: size() const -> unsigned long long {
  48. //array_length = sizeof(data)/sizeof(T);
  49. return array_length;
  50. }
  51.  
  52. template <typename T>
  53. auto infinite_array<T> :: operator[](unsigned long long idx) -> T& {
  54. //std::cout << "Accessing element at idx " << idx << std::endl;
  55. if(idx+1 > size()) {
  56. resize(idx+1);
  57. }
  58. return data[idx];
  59. }
  60.  
  61.  
  62. int main() {
  63. infinite_array<int> ar;
  64. for(int i = 0; i < 10; ++i) {
  65. ar[i] = i;
  66. }
  67.  
  68. ar[30] = ar[31] = 10;
  69.  
  70.  
  71. for(int i = 0; i < ar.size(); ++i)
  72. std::cout << ar[i] << ' ';
  73. std::cout << std::endl;
  74.  
  75. return 0;
  76. }
Success #stdin #stdout 0s 3472KB
stdin
Standard input is empty
stdout
Resize with idx 1

Resize with idx 2
0 
Resize with idx 3
0 1 
Resize with idx 4
0 1 2 
Resize with idx 5
0 1 2 3 
Resize with idx 6
0 1 2 3 4 
Resize with idx 7
0 1 2 3 4 5 
Resize with idx 8
0 1 2 3 4 5 6 
Resize with idx 9
0 1 2 3 4 5 6 7 
Resize with idx 10
0 1 2 3 4 5 6 7 8 
Resize with idx 31
0 1 2 3 4 5 6 7 8 9 
Resize with idx 32
0 1 2 3 4 5 6 7 8 9 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 
0 1 2 3 4 5 6 7 8 9 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 10