Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <iostream>
- using namespace std;
- class Vector {
- public:
- Vector() : size(0), capacity(4), arr (new int[4]) {}
- Vector(const int vector_capacity) : size(0), capacity(vector_capacity), arr(new int[vector_capacity]) {}
- void Push_back(const int value) {
- if (size == capacity) {
- int* temp = new int[capacity * 2];
- for (int i = 0; i < size; i++) {
- temp[i] = arr[i];
- }
- delete[] arr;
- arr = temp;
- capacity *= 2;
- }
- arr[size] = value;
- size++;
- total_number_elements++;
- }
- void Pop_back() {
- if (size > 0) {
- arr[size - 1] = 0;
- size--;
- total_number_elements--;
- }
- }
- int Size() {
- return size;
- }
- int Capacity() {
- return capacity;
- }
- void Insert(const int index, const int value) {
- if (index < 0 || index >= size) {
- cout << "Invalid index" << endl;
- return;
- }
- if (size == capacity) {
- int* temp = new int[capacity * 2];
- for (int i = 0; i < size; i++) {
- temp[i] = arr[i];
- }
- delete[] arr;
- arr = temp;
- capacity *= 2;
- }
- for (int i = size; i > index; i--) {
- arr[i] = arr[i - 1];
- }
- arr[index] = value;
- size++;
- total_number_elements++;
- }
- void Erase(const int index) {
- if (index < 0 || index >= size) {
- cout << "Invalid index" << endl;
- return;
- }
- for (int i = index; i < size - 1; i++) {
- arr[i] = arr[i + 1];
- }
- arr[size - 1] = 0;
- size--;
- total_number_elements--;
- }
- int GetValue(const int index) {
- if (index < 0 || index >= size) {
- cout << "Invalid index" << endl;
- abort;
- }
- return arr[index];
- }
- void SetValue(const int index, const int value) {
- if (index < 0 || index >= size) {
- cout << "Invalid index" << endl;
- return;
- }
- arr[index] = value;
- }
- ~Vector() {
- delete[] arr;
- }
- private:
- int size;
- int capacity;
- int* arr;
- };
- int Vector::total_number_elements = 0;
- int main() {
- Vector my_vector;
- my_vector.Push_back(10);
- cout << "Size: " << my_vector.Size() << " Capacity: " << my_vector.Capacity() << endl;
- my_vector.Erase(0);
- cout << "Size: " << my_vector.Size() << " Capacity: " << my_vector.Capacity() << endl;
- for (int i = 0; i < 10; i++) {
- my_vector.Push_back(i + 1);
- }
- for (int i = 0; i < my_vector.Size(); i++) {
- cout << my_vector.GetValue(i) << " ";
- }
- cout << endl;
- cout << "Size: " << my_vector.Size() << " Capacity: " << my_vector.Capacity() << endl;
- my_vector.SetValue(2, 13);
- my_vector.Insert(4, 12);
- for (int i = 0; i < my_vector.Size(); i++) {
- cout << my_vector.GetValue(i) << " ";
- }
- cout << endl;
- cout << "Size: " << my_vector.Size() << " Capacity: " << my_vector.Capacity() << endl;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement