|
| 1 | +#ifndef __ARRAY__ |
| 2 | +#define __ARRAY__ |
| 3 | + |
| 4 | +#include <cstddef> |
| 5 | +#include <initializer_list> |
| 6 | + |
| 7 | +namespace std { |
| 8 | + |
| 9 | +template <typename T, size_t N> |
| 10 | +class array { |
| 11 | +public: |
| 12 | + typedef T value_type; |
| 13 | + typedef T* pointer; |
| 14 | + typedef const T* const_pointer; |
| 15 | + typedef value_type& reference; |
| 16 | + typedef const value_type& const_reference; |
| 17 | + typedef pointer iterator; |
| 18 | + typedef const_pointer const_iterator; |
| 19 | + typedef size_t size_type; |
| 20 | + |
| 21 | +private: |
| 22 | + value_type _data[N ? N : 1]; |
| 23 | + |
| 24 | +public: |
| 25 | + array() = default; |
| 26 | + array(std::initializer_list<T> init) { |
| 27 | + if (init.size() != N) { |
| 28 | + // error |
| 29 | + } |
| 30 | + size_t i = 0; |
| 31 | + for(const auto& item : init) { |
| 32 | + _data[i++] = item; |
| 33 | + } |
| 34 | + } |
| 35 | + array& operator=(const array& other) = default; |
| 36 | + |
| 37 | + reference operator[](size_type i) { return _data[i]; } |
| 38 | + const_reference operator[](size_type i) const { return _data[i]; } |
| 39 | + reference front() { return _data[0]; } |
| 40 | + const_reference front() const { return _data[0]; } |
| 41 | + reference back() { return _data[N - 1]; } |
| 42 | + const_reference back() const { return _data[N - 1]; } |
| 43 | + pointer data() noexcept { return _data; } |
| 44 | + const_pointer data() const noexcept { return _data; } |
| 45 | + reference at(size_type pos) { return _data[pos]; } |
| 46 | + const_reference at(size_type pos) const { return _data[pos]; } |
| 47 | + |
| 48 | + iterator begin() noexcept { return _data; } |
| 49 | + const_iterator begin() const noexcept { return _data; } |
| 50 | + const_iterator cbegin() const noexcept { return _data; } |
| 51 | + iterator end() noexcept { return _data + N; } |
| 52 | + const_iterator end() const noexcept { return _data + N; } |
| 53 | + const_iterator cend() const noexcept { return _data + N; } |
| 54 | + |
| 55 | + bool empty() const noexcept { return begin() == end(); } |
| 56 | + size_type size() const noexcept { return N; } |
| 57 | + size_type max_size() const noexcept { return N; } |
| 58 | + |
| 59 | + void fill(const_reference value) { |
| 60 | + for (auto i = 0u; i < N; ++i) { |
| 61 | + _data[i] = value; |
| 62 | + } |
| 63 | + } |
| 64 | +}; |
| 65 | + |
| 66 | +} |
| 67 | + |
| 68 | +#endif |
0 commit comments