Related Articles

# How to implement our own Vector Class in C++?

• Difficulty Level : Medium
• Last Updated : 29 Oct, 2020

Given task is to implement a class in C++ which behaves just like the Vector class.
Vectors are same as dynamic arrays with the ability to resize itself automatically when an element is inserted or deleted, with their storage being handled automatically by the container. Vector elements are placed in contiguous storage so that they can be accessed and traversed using iterators. In vectors, data is inserted at the end. Inserting at the end takes differential time, as sometimes there may be a need of extending the array. Removing the last element takes only constant time because no resizing happens. Inserting and erasing at the beginning or in the middle is linear in time.

We can also make the vector class generic using templates.
Certain functions associated with the Vector that we will implement are:

Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.  To complete your preparation from learning a language to DS Algo and many more,  please refer Complete Interview Preparation Course.

In case you wish to attend live classes with experts, please refer DSA Live Classes for Working Professionals and Competitive Programming Live for Students.

• void push(int data): This function takes one element and inserts it at the last. Amortized time complexity is O(1).
• void push(int data, int index): It inserts data at the specified index. Time complexity is O(1).
• int get(int index): It is used to get the element at the specified index. Time complexity is O(1).
• void pop(): It deletes the last element. Time complexity is O(1).
• int size(): It returns the size of the vector i.e, number of elements in the vector. Time complexity is O(1).
• int getcapacity(): It returns the capacity of the vector. Time complexity is O(1).
• void print(): It is used to print array elements. Time complexity is O(N), where N is the size of the vector.

Below is the implementation of our own Vector class.

## CPP

 `// Self implementation of``// the Vector Class in C++` `#include ``using` `namespace` `std;``template` `<``typename` `T> ``class` `vectorClass``{` `    ``// arr is the integer pointer``    ``// which stores the address of our vector``    ``T* arr;` `    ``// capacity is the total storage``    ``// capacity of the vector``    ``int` `capacity;` `    ``// current is the number of elements``    ``// currently present in the vector``    ``int` `current;` `public``:``    ``// Default constructor to initialise``    ``// an initial capacity of 1 element and``    ``// allocating storage using dynamic allocation``    ``vectorClass()``    ``{``        ``arr = ``new` `T;``        ``capacity = 1;``        ``current = 0;``    ``}` `    ``// Function to add an element at the last``    ``void` `push(T data)``    ``{` `        ``// if the number of elements is equal to the``        ``// capacity, that means we don't have space to``        ``// accommodate more elements. We need to double the``        ``// capacity``        ``if` `(current == capacity) {``            ``T* temp = ``new` `T[2 * capacity];` `            ``// copying old array elements to new array``            ``for` `(``int` `i = 0; i < capacity; i++) {``                ``temp[i] = arr[i];``            ``}` `            ``// deleting previous array``            ``delete``[] arr;``            ``capacity *= 2;``            ``arr = temp;``        ``}` `        ``// Inserting data``        ``arr[current] = data;``        ``current++;``    ``}` `    ``// function to add element at any index``    ``void` `push(``int` `data, ``int` `index)``    ``{` `        ``// if index is equal to capacity then this``        ``// function is same as push defined above``        ``if` `(index == capacity)``            ``push(data);``        ``else``            ``arr[index] = data;``    ``}` `    ``// function to extract element at any index``    ``T get(``int` `index)``    ``{` `        ``// if index is within the range``        ``if` `(index < current)``            ``return` `arr[index];``    ``}` `    ``// function to delete last element``    ``void` `pop() { current--; }` `    ``// function to get size of the vector``    ``int` `size() { ``return` `current; }` `    ``// function to get capacity of the vector``    ``int` `getcapacity() { ``return` `capacity; }` `    ``// function to print array elements``    ``void` `print()``    ``{``        ``for` `(``int` `i = 0; i < current; i++) {``            ``cout << arr[i] << ``" "``;``        ``}``        ``cout << endl;``    ``}``};` `// Driver code``int` `main()``{``    ``vectorClass<``int``> v;``    ``vectorClass<``char``> v1;``    ``v.push(10);``    ``v.push(20);``    ``v.push(30);``    ``v.push(40);``    ``v.push(50);``    ``v1.push(71);``    ``v1.push(72);``    ``v1.push(73);``    ``v1.push(74);` `    ``cout << ``"Vector size : "` `<< v.size() << endl;``    ``cout << ``"Vector capacity : "` `<< v.getcapacity() << endl;` `    ``cout << ``"Vector elements : "``;``    ``v.print();` `    ``v.push(100, 1);` `    ``cout << ``"\nAfter updating 1st index"` `<< endl;` `    ``cout << ``"Vector elements of type int : "` `<< endl;``    ``v.print();``    ``// This was possible because we used templates``    ``cout << ``"Vector elements of type char : "` `<< endl;``    ``v1.print();``    ``cout << ``"Element at 1st index of type int: "` `<< v.get(1)``         ``<< endl;``    ``cout << ``"Element at 1st index of type char: "``         ``<< v1.get(1) << endl;` `    ``v.pop();``    ``v1.pop();` `    ``cout << ``"\nAfter deleting last element"` `<< endl;` `    ``cout << ``"Vector size of type int: "` `<< v.size() << endl;``    ``cout << ``"Vector size of type char: "` `<< v1.size()``         ``<< endl;``    ``cout << ``"Vector capacity of type int : "``         ``<< v.getcapacity() << endl;``    ``cout << ``"Vector capacity of type char : "``         ``<< v1.getcapacity() << endl;` `    ``cout << ``"Vector elements of type int: "``;``    ``v.print();``    ``cout << ``"Vector elements of type char: "``;``    ``v1.print();` `    ``return` `0;``}`
Output
```Vector size : 5
Vector capacity : 8
Vector elements : 10 20 30 40 50

After updating 1st index
Vector elements of type int :
10 100 30 40 50
Vector elements of type char :
G H I J
Element at 1st index of type int: 100
Element at 1st index of type char: H

After deleting last element
Vector size of type int: 4
Vector size of type char: 3
Vector capacity of type int : 8
Vector capacity of type char : 4
Vector elements of type int: 10 100 30 40
Vector elements of type char: G H I

```

My Personal Notes arrow_drop_up