From 57b29ef0f28c587d93ffd5a1a5975629af3a7455 Mon Sep 17 00:00:00 2001 From: Stoycho Kyosev <68247567+stoychoX@users.noreply.github.com> Date: Wed, 13 Apr 2022 15:08:14 +0300 Subject: Add files via upload --- pract SI/week8/vector.cpp | 76 +++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 76 insertions(+) create mode 100644 pract SI/week8/vector.cpp (limited to 'pract SI/week8/vector.cpp') diff --git a/pract SI/week8/vector.cpp b/pract SI/week8/vector.cpp new file mode 100644 index 0000000..12a763d --- /dev/null +++ b/pract SI/week8/vector.cpp @@ -0,0 +1,76 @@ +#include "vector.h" +#include + +void vector::free() { + delete[] data; +} + +void vector::copyFrom(const vector& other) { + size = other.size; + capacity = other.capacity; + + data = new int[capacity]; + + for (int i = 0; i < size; i++) + data[i] = other.data[i]; +} + +void vector::resize() { + capacity = 2 * capacity; + + int* newMemory = new int[capacity]; + + for (int i = 0; i < size; i++) + newMemory[i] = data[i]; + + delete[] data; + data = newMemory; +} + +vector::vector() { + size = 0; + capacity = 8; + data = new int[capacity]; +} + +vector::vector(const vector& other) { + copyFrom(other); +} + +vector& vector::operator=(const vector& other) +{ + if (this != &other) { + free(); + copyFrom(other); + } + return *this; +} + +size_t vector::getSize() const { + return size; +} + +void vector::push_back(int elem) { + if (size == capacity) + resize(); + + data[size++] = elem; +} + + + +int& vector::operator[](size_t index) { + if (index >= size) + throw std::exception("out of range"); + return data[index]; +} + +const int vector::operator[](size_t index) const { + if (index >= size) + throw std::exception("out of range"); + return data[index]; +} + +vector::~vector() { + free(); +} -- cgit v1.3.1-23-gd82d