diff options
Add files via upload
3 files changed, 121 insertions, 0 deletions
| -rw-r--r-- | pract SI/week8/Source.cpp | 16 | ||||
| -rw-r--r-- | pract SI/week8/vector.cpp | 76 | ||||
| -rw-r--r-- | pract SI/week8/vector.h | 29 |
diff --git a/pract SI/week8/Source.cpp b/pract SI/week8/Source.cpp new file mode 100644 index 0000000..fc8b5ed --- /dev/null +++ b/pract SI/week8/Source.cpp @@ -0,0 +1,16 @@ +#include<iostream>
+#include"vector.h"
+
+int main() {
+ vector v;
+
+ for (int i = 0; i < 100; i++)
+ v.push_back(i);
+
+ v[78] = 1000;
+
+ for (int i = 0; i < 100; i++)
+ std::cout << v[i] << " ";
+
+ std::cout << std::endl << v.getSize();
+}
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<exception>
+
+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();
+}
diff --git a/pract SI/week8/vector.h b/pract SI/week8/vector.h new file mode 100644 index 0000000..bf7c947 --- /dev/null +++ b/pract SI/week8/vector.h @@ -0,0 +1,29 @@ +#ifndef VECTOR_HEADER
+#define VECTOR_HEADER
+
+class vector {
+private:
+ int* data;
+ size_t size;
+ size_t capacity;
+
+ void free();
+ void copyFrom(const vector&);
+ void resize(); // x2 memory
+public:
+ vector();
+ vector(const vector&);
+
+ vector& operator=(const vector&);
+
+ size_t getSize() const;
+ void push_back(int);
+
+ int& operator[](size_t);
+ const int operator[](size_t) const;
+
+ ~vector();
+};
+
+#endif
+
|
