fork download
  1. #include <cstddef>
  2. #include <iostream>
  3. #include <iterator>
  4. #include <algorithm>
  5.  
  6. template<typename T>
  7. class my_array{
  8. T* data_;
  9. std::size_t size_;
  10.  
  11. public:
  12.  
  13. my_array()
  14. : data_(NULL), size_(0)
  15. {}
  16. my_array(std::size_t size)
  17. : data_(new T[size]), size_(size)
  18. {}
  19. my_array(const my_array<T>& other){
  20. size_ = other.size_;
  21. data_ = new T[size_];
  22. for (std::size_t i = 0; i<size_; i++)
  23. data_[i] = other.data_[i];
  24. }
  25. my_array(const T* first, const T* last){
  26. size_ = last - first;
  27. data_ = new T[size_];
  28.  
  29. for (std::size_t i = 0; i<size_; i++)
  30. data_[i] = first[i];
  31. }
  32.  
  33. ~my_array(){
  34. delete [] data_;
  35. }
  36. const my_array<T>& operator=(const my_array<T>& other){
  37. size_ = other.size_;
  38. data_ = new T[size_];
  39. for (std::size_t i = 0; i<size_; i++)
  40. data_[i] = other.data_[i];
  41. return other;
  42. }
  43. const T& operator[](std::size_t idx) const {return data_[idx];}
  44. T& operator[](std::size_t& idx) {return data_[idx];}
  45. std::size_t size(){return size_;}
  46.  
  47. T* begin(){return data_;}
  48. T* end(){return data_+size_;}
  49. };
  50.  
  51. template<typename T>
  52. void print(T t) {
  53. std::cout << t << std::endl;
  54. }
  55.  
  56. int main(){
  57.  
  58.  
  59. typedef float scalar_t;
  60. scalar_t list [] = {1, 3, 5, 2, 4, 3, 5, 10, 10};
  61. my_array<scalar_t> a(list, list+sizeof(list)/sizeof(scalar_t));
  62.  
  63. // works!
  64. for (scalar_t* it = a.begin(), *end = a.end();
  65. it != end; ++it)
  66. std::cout << ' ' << *it;
  67. std::cout << std::endl;
  68.  
  69. // works!
  70. std::for_each(a.begin(), a.end(), print<scalar_t>);
  71. std::cout << std::endl;
  72.  
  73. // works!
  74. my_array<int> b(a.size());
  75. std::copy(a.begin(), a.end(), b.begin());
  76.  
  77. // works!
  78. scalar_t* end = std::remove(a.begin(), a.end(), 5);
  79. std::for_each(a.begin(), end, print<scalar_t>);
  80. std::cout << std::endl;
  81.  
  82. // works!
  83. std::random_shuffle(a.begin(), end);
  84. std::for_each(a.begin(), end, print<scalar_t>);
  85. std::cout << std::endl;
  86.  
  87. // works!
  88. std::cout << "Counts of 3 in array = " << std::count(a.begin(), end, 3) << std::endl << std::endl;
  89.  
  90. // works!
  91. std::sort(a.begin(), end);
  92. std::for_each(a.begin(), end, print<scalar_t>);
  93. std::cout << std::endl;
  94.  
  95. // works!
  96. if (!std::binary_search(a.begin(), a.end(), 5))
  97. std::cout << "Removed!" << std::endl;
  98.  
  99. return 0;
  100. }
  101.  
Success #stdin #stdout 0s 2988KB
stdin
Standard input is empty
stdout
 1 3 5 2 4 3 5 10 10
1
3
5
2
4
3
5
10
10

1
3
2
4
3
10
10

3
4
3
10
1
10
2

Counts of 3 in array = 2

1
2
3
3
4
10
10

Removed!