Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <cstddef>
- #include <memory>
- #include <cstring>
- #include <utility>
- #include <stdexcept>
- namespace my {
- template <class T>
- class vector {
- public:
- explicit vector(size_t count = 0)
- : _data((T*)new char[(count ? count : 1)*sizeof(T)])
- , _size(count)
- , _capacity(count ? count : 1)
- {}
- vector(const vector<T>& other)
- : _data((T*)new char[(other._size ? other._size : 1)*sizeof(T)])
- , _size(0)
- , _capacity(other._size ? other._size : 1)
- {
- for(int i = 0; i < other._size; ++i) {
- push_back(other._data[i]);
- }
- }
- vector(vector<T>&& other) = default;
- ~vector() {
- for(T* p = _data.release(), *end = p + _size; p != end; ++p) {
- p->~T();
- }
- }
- void swap(vector<T>& other) {
- std::swap(_size, other._size);
- std::swap(_capacity, other._capacity); std::swap(_data, other._data);
- }
- T& at(size_t index) {
- if(index >= _size) {
- throw std::out_of_range("out of range in method \"at\" in my::vector");
- }
- return operator[](index);
- }
- T at(size_t index) const {
- if(index >= _size) {
- throw std::out_of_range("out of range in method \"at\" in my::vector");
- }
- return operator[](index);
- }
- T& operator[](size_t index) {
- return _data[index];
- }
- T operator[](size_t index) const {
- return _data[index];
- }
- bool empty() const {
- return !_size;
- }
- size_t size() const {
- return _size;
- }
- size_t capacity() const {
- return _capacity;
- }
- void push_back(const T& e) {
- if(_size == _capacity) {
- reserve(_capacity * 2);
- }
- new(_data.get() + _size) T(e);
- _size++;
- }
- void push_back(T&& e) {
- if(_size == _capacity) {
- reserve(_capacity * 2);
- }
- new(_data.get() + _size) T(std::move(e));
- _size++;
- }
- void reserve(size_t new_capacity) {
- if(new_capacity <= _capacity) return;
- std::unique_ptr<T[]> new_data((T*)new char[new_capacity*sizeof(T)]);
- for(int i = 0; i < _size; ++i) {
- new(new_data.get() + i) T(std::move(_data[i]));
- }
- _data.swap(new_data);
- _capacity = new_capacity;
- }
- private:
- std::unique_ptr<T[]> _data;
- size_t _size;
- size_t _capacity;
- };
- template <class T>
- void swap(vector<T>& lhs, vector<T>& rhs) {
- lhs.swap(rhs);
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement