| 8 | |
| 9 | template <typename T> |
| 10 | class vector { |
| 11 | public: |
| 12 | using value_type = T; |
| 13 | using size_type = size_t; |
| 14 | |
| 15 | using iterator = T*; |
| 16 | using const_iterator = const T*; |
| 17 | |
| 18 | private: |
| 19 | T* data_; |
| 20 | size_type size_; |
| 21 | size_type capacity_; |
| 22 | |
| 23 | // Helper function for geometric growth |
| 24 | void grow_capacity() { |
| 25 | size_type new_capacity = capacity_ == 0 ? 1 : capacity_ * 2; |
| 26 | reserve(new_capacity); |
| 27 | } |
| 28 | |
| 29 | public: |
| 30 | // Constructors |
| 31 | vector() noexcept : data_(nullptr), size_(0), capacity_(0) {} |
| 32 | |
| 33 | explicit vector(size_type count, const T& value = T()) |
| 34 | : data_(allocate(count)), size_(count), capacity_(count) |
| 35 | { |
| 36 | for (size_type i = 0; i < size_; ++i) { |
| 37 | new (&data_[i]) T(value); // Use placement new for construction |
| 38 | } |
| 39 | } |
| 40 | |
| 41 | // Copy Constructor |
| 42 | vector(const vector& other) |
| 43 | : data_(allocate(other.size_)), size_(other.size_), capacity_(other.size_) |
| 44 | { |
| 45 | for (size_type i = 0; i < size_; ++i) { |
| 46 | new (&data_[i]) T(other.data_[i]); // Use placement new for construction |
| 47 | } |
| 48 | } |
| 49 | |
| 50 | // Destructor |
| 51 | ~vector() { |
| 52 | clear(); // Destroy elements |
| 53 | deallocate(data_); // Deallocate memory |
| 54 | } |
| 55 | |
| 56 | // Copy Assignment Operator |
| 57 | vector& operator=(const vector& other) { |
| 58 | if (this != &other) { |
| 59 | // A simple but not fully exception-safe implementation |
| 60 | clear(); |
| 61 | deallocate(data_); |
| 62 | |
| 63 | data_ = allocate(other.capacity_); |
| 64 | capacity_ = other.capacity_; |
| 65 | size_ = other.size_; |
| 66 | for (size_type i = 0; i < size_; ++i) { |
| 67 | new (&data_[i]) T(other.data_[i]); |
nothing calls this directly
no outgoing calls
no test coverage detected