Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #ifndef DARRAY_H__
- #define DARRAY_H__
- #include <iostream>
- template<typename T>
- class Darray
- {
- public:
- Darray()
- :m_tab{new T[8U]},
- m_size{8U},
- m_capacity{8U}
- {
- for (std::size_t i = 0; i < m_capacity; ++i)
- m_tab[i] = T{};
- }
- Darray(std::size_t initial_capacity)
- :m_tab{new T[initial_capacity]},
- m_size{initial_capacity},
- m_capacity{initial_capacity}
- {
- for (std::size_t i = 0; i < m_capacity; ++i)
- m_tab[i] = T{};
- }
- Darray(const Darray& another)
- :m_tab{new T[another.m_capacity]},
- m_size{another.m_size},
- m_capacity{another.m_capacity}
- {
- for (std::size_t i = 0; i < m_size; ++i)
- m_tab[i] = another[i];
- }
- Darray& operator=(const Darray& another)
- {
- m_size = another.m_size;
- m_capacity = another.m_capacity;
- delete[] m_tab;
- m_tab = new T[m_capacity];
- for (std::size_t i = 0; i < m_size; ++i)
- m_tab[i] = another[i];
- return *this;
- }
- Darray(Darray&& another)
- :m_tab{another.m_tab},
- m_size{another.m_size},
- m_capacity{another.m_capacity}
- {
- another.m_size = another.m_capacity = 0;
- another.m_tab = nullptr;
- }
- Darray& operator=(Darray&& another)
- {
- m_size = another.m_size;
- m_capacity = another.m_capacity;
- delete[] m_tab;
- m_tab = another.m_tab;
- another.m_size = another.m_capacity = 0;
- another.m_tab = nullptr;
- return *this;
- }
- T* begin()
- {
- return &m_tab[0];
- }
- const T* begin() const
- {
- return &m_tab[size];
- }
- T* end()
- {
- return &m_tab[m_size];
- }
- const T* end() const
- {
- return &m_tab[m_size];
- }
- size_t size() const
- {
- return m_size;
- }
- size_t capacity() const
- {
- return m_capacity;
- }
- void resize(size_t new_size)
- {
- if (new_size <= m_capacity)
- return;
- T* tp = new T[new_size];
- m_capacity = new_size;
- unsigned i;
- for (i = 0; i < m_size; ++i)
- tp[i] = m_tab[i];
- for (; i < m_capacity; ++i)
- m_tab[i] = T{};
- delete[] m_tab;
- m_tab = tp;
- }
- void push_back(const T& value)
- {
- if(m_size == m_capacity)
- resize(2 * m_capacity);
- m_tab[m_size++] = value;
- }
- T& operator[](size_t pos)
- {
- return m_tab[pos];
- }
- const T& operator[](size_t pos) const
- {
- return m_tab[pos];
- }
- ~Darray()
- {
- delete[] m_tab;
- }
- private:
- T* m_tab;
- std::size_t m_size;
- std::size_t m_capacity;
- };
- #endif // DARRAY_H
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement