Vector Class Implementation Using C++

Filed Under: C++
Vector Class Implementation Using C

Vectors are one of the most used data structures in the programming world. Today we will learn vector class in C++. We will start by learning about vectors and later move to code a vector class that will feature basic vector properties and functions.

What Is A Vector ?

A vector is simply a dynamic array. This might sound very normal but this particular property is the basis of the existence of vectors. In real-life applications we never know the amount of raw data that needs to be processed, this rules out the choice of using fixed-size arrays. We can not limit the amount of raw data, hence we need to use something dynamic in nature. This gives birth to vectors. Unlike arrays, vectors offer scalability, meaning that their size is not limited.

Basic Features Of A Vector

Following are some of the core features of a vector.

  • Dynamic Size
  • Random Access
  • Push(): Insertion of data at the end
  • Pop(): Deletion of data from the end
  • Size(): Current size of the vector
  • Capacity(): The ratio of filled to empty data units

Vector Class Implementation Using C++

Let’s quickly jump to the code. For the freedom of data types, we will implement a template vector class using C++.

Data Members

A vector basically consists of the following data members.

  1. T *arr: Pointer to a data type(say T). This pointer defines an array of a template data type T that represents a general data type like integer, string, etc.
  2. int cs: Represents the current size of the vector.
  3. int ms: It implies the maximum size of the vector(this size is dynamic in nature)

Member Functions

Below are some of the most essential member functions of a vector class.

  1. Vector(): Default constructor of the vector class
  2. void push(T data): This function inserts data at the end of the vector
  3. void pop(): It deletes the last element in the vector
  4. bool is_empty(): Returns true if no elements are there in the array otherwise false
  5. int size(): Return the current_size of the vector
  6. float capacity(): Returns the ratio of current_size to the maximum_size of the vector
  7. T operator[](const int i): Returns the element at the ith index

Code

template <typename T>
class Vector
{
        T *arr;
        int cs;
        int ms;
public:
        Vector()
        int size() const;
        int is_empty() const;
        float capacity() const;
        void push(const T data);
        void pop();
        T operator[](const int i)
};

Note: The data members are declared privately so that no external function can alter or access them.

Member Functions

Let’s look at the member functions in this class.

1. Vector()

       Vector()
       {
                cs = 0;
                ms = 1;
                arr = new T[ms];
       };

2. size()

int size() const
{
        return cs;
}

3. is_empty()

int is_empty() const
{
        return cs == 0;
}

4. capacity()

float capacity() const
{       
        return float((1.0 * cs)/(1.0 * ms));
}

5. push(T data)

void push(const T data)
{
        if(cs == ms)
        {
                // double the size of the array
                ms *= 2;

                // generate new array
                T *old_arr = arr;
                arr = new T[ms];

                // copy the elements of the old arry
                // into new array
                for(int i = 0; i < cs; i++)
                        arr[i] = old_arr[i];

                //delete the old_arr to prevent memory leaks
                delete [] old_arr;
        }

        //insert the data and increment the current size
        arr[cs++] = data;

        return;
}

6. pop()

void pop()
{
        if(is_empty())
                return;

        cs--;
}

7. operator [](const int i)

T operator [](const int i)
{
       return arr[i];
}

Complete Implementation of Vector Class in C++

#include <iostream>

using namespace std;

template <typename T>
class Vector
{
	T *arr;
	int cs;
	int ms;
public:
	Vector()
	{
		cs = 0;
		ms = 1;
		arr = new T[ms];
	};

	int size() const
	{
        	return cs;
	}

	int is_empty() const
	{
	        return cs == 0;
	}

	float capacity() const
	{
        	return float((1.0 * cs)/(1.0 * ms));
	}

	void push(const T data)
	{
	        if(cs == ms)
	        {
	                // double the size of the array
	                ms *= 2;

	                // generate new array
	                T *old_arr = arr;
	                arr = new T[ms];

        	        // copy the elements of the old arry
	                // into new array
                	for(int i = 0; i < cs; i++)
        	                arr[i] = old_arr[i];
	
	                //delete the old_arr to prevent memory leaks
	                delete [] old_arr;
        	}

	        //insert the data and increment the current size
        	arr[cs++] = data;

	        return;
	}

	void pop()
	{
	        if(is_empty())
	                return;

        	cs--;
	}

	T operator [](const int i)
	{
		return arr[i];
	}
};

void print_vector(Vector <int> v)
{
	cout << "The vector contents are:" << endl;
	for(int i = 0; i < v.size(); i++)
		cout << v[i] << " ";
	cout << endl;
}

int main()
{
	cout << "Enter the elements (-1 to stop)" << endl;

	Vector <int> v;
	while(true)
	{
		int ele;
		cin >> ele;
		
		if(ele == -1)
			break;
		v.push(ele);
	}

	print_vector(v);

	cout << "Deleting the last 2 elements" << endl;
	v.pop();
	v.pop();

	print_vector(v);

	cout << "The size of the vector is: " << v.size() << endl;
}
Template Vector Class Code
Template Vector Class Code

Output

Vector Class Output
Vector Class Output

Conclusion

In today’s article, we discussed the major difference between a vector an array. Then we discussed the basic features of a vector and a vector class. In the end, we coded a template vector class in C++. That’s all for today, thanks for reading.

References

To learn more about vectors you can refer to the following websites.

https://en.cppreference.com/w/cpp/container/vector

close
Generic selectors
Exact matches only
Search in title
Search in content