Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #pragma once
- #include <cassert>
- #include <cstdlib>
- #include <new>
- #include <utility>
- #include <cstring>
- template <typename T>
- class Vector {
- public:
- Vector() = default;
- Vector(size_t size)
- :data_(Allocate(size)){
- data_ = new T[size];
- capacity_ = size;
- size_= size;
- }
- Vector(const Vector<T>& other)
- :data_(Allocate(other.size_)){
- for(size_t i=0;i<other.size_;++i)
- data_[i] = T(other.data_[i]);
- size_ = other.size_;
- capacity_=other.capacity_;
- }
- /*
- Vector(Vector<T>&& other)
- {
- T* new_data_=Allocate(other.size);
- new_data_ = new T[other.size_];
- std::memmove(other.data_,new_data_,other.size_);
- other.~Vector();
- }*/
- static void CopyConstruct(T* from, T* to, size_t len) {
- for (size_t i = 0; i<len; ++i){
- to[i]=from[i];
- }
- }
- size_t Size() const noexcept {
- return size_;
- }
- size_t Capacity() const noexcept {
- return capacity_;
- }
- const T& operator[](size_t index) const noexcept {
- return const_cast<Vector&>(*this)[index];
- }
- T& operator[](size_t index) noexcept {
- assert(index < size_);
- return data_[index];
- }
- static T* Allocate(size_t n){
- return n!=0? static_cast<T*>(operator new(n*sizeof(T))):nullptr;
- }
- static void Deallocate(T* buf, size_t size) noexcept{
- operator delete[](buf,size);
- }
- ~Vector(){
- DestroyN(data_,size_);
- Deallocate(data_,size_);
- }
- static void DestroyN(T* buf, size_t n) noexcept {
- for (size_t i = 0; i != n; ++i) {
- Destroy(buf + i);
- }
- }
- // Вызывает деструктор объекта по адресу buf
- static void Destroy(T* buf) noexcept {
- buf->~T();
- }
- void Reserve(size_t new_capacity){
- if (new_capacity <= capacity_) {
- return;
- }
- T* new_data = Allocate(new_capacity);
- CopyConstruct(data_, new_data,size_);
- DestroyN(data_, size_);
- Deallocate(data_,size_);
- data_ = new_data;
- capacity_ = new_capacity;
- }
- private:
- T* data_ = nullptr;
- size_t capacity_ = 0;
- size_t size_ = 0;
- };
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement