Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include "pch.h"
- #include "DynamicArray.h"
- #include <exception>
- #include <iostream>
- using namespace std;
- DynamicArray::DynamicArray(int capacity) : capacity{ capacity }, n{ 0 }
- {
- this->v = (TElem*)malloc(capacity * sizeof(TElem));
- }
- DynamicArray::~DynamicArray()
- {
- free(this->v);
- this->v = NULL;
- }
- int DynamicArray::size() const
- {
- return this->n;
- }
- TElem DynamicArray::getElement(int pos) const
- {
- return this->v[pos];
- }
- TElem DynamicArray::setElement(int pos, TElem newElem)
- {
- int oldElem = this->v[pos];
- this->v[pos] = newElem;
- for (int i = 0; i < this->n; ++i) {
- cout << v[i] << ' ';
- }
- cout << "\n---------------\n";
- return oldElem;
- }
- void DynamicArray::addToEnd(TElem newElem)
- {
- if (n == capacity)
- {
- this->capacity *= 2;
- TElem* aux = (TElem*)realloc(this->v, this->capacity * sizeof(TElem));
- this->v = aux;
- }
- this->v[n] = newElem;
- n++;
- for (int i = 0; i < this->n; ++i) {
- cout << v[i] << ' ';
- }
- cout << "\n---------------\n";
- }
- void DynamicArray::addToPosition(int pos, TElem newElem)
- {
- if (n + 1 == capacity)
- {
- this->capacity *= 2;
- TElem* aux = (TElem*)realloc(this->v, this->capacity * sizeof(TElem));
- this->v = aux;
- }
- if (pos == n) {
- v[pos] = newElem;
- ++n;
- for (int i = 0; i < this->n; ++i) {
- cout << v[i] << ' ';
- }
- cout << "\n---------------\n";
- return;
- }
- // 0 1 2 3 4 5
- // 5 1
- for (int i = n; i > pos; --i) {
- v[i] = v[i - 1];
- }
- v[pos] = newElem;
- ++n;
- for (int i = 0; i < this->n; ++i) {
- cout << v[i] << ' ';
- }
- cout << "\n---------------\n";
- }
- TElem DynamicArray::remove(int pos)
- {
- if (pos == n - 1) {
- --n;
- for (int i = 0; i < this->n; ++i) {
- cout << v[i] << ' ';
- }
- cout << "\n---------------\n";
- return v[pos];
- }
- int oldElem = v[pos];
- for (int i = pos; i < n - 1; ++i) {
- v[i] = v[i + 1];
- }
- --n;
- for (int i = 0; i < this->n; ++i) {
- cout << v[i] << ' ';
- }
- cout << "\n---------------\n";
- return oldElem;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement