Vectors (Dynamic Arrays) in C++ Programming

In this article we are going to learn about vectors. Before understanding vectors. let’s first discuss about arrays. You have used arrays a lot where you can store data in a sequential way. There is lot of use of arrays since programming has been started. You are using arrays in implementation of Queue stack and in many more virtual Data structures. You can say arrays are lifeline of programmers.

So what is problem with array? No! There is no problem with standard arrays. It’s limitation of arrays that is stopping you to do a lot with arrays. Let’s first discuss about features of standard arrays in brief.



Properties of arrays
  • Array stores data in sequential way.
  • Arrays Always created with the fixed size. You have to define the size of array while creation.
  • Time complexity of accessing elements is just O(1) because all data sequential way.
  • Memory allocation for the array is at compile time in stack.

int arr[10] ;
here we have decided the size of array at compile time.


There is a lot of features of arrays but that are not relevant for this article. We will talk about them in another article. Main issue with array is that it is fixed size data structure that once you created an array you can not increase the size of array. You can not insert more element in array.

For solving this problem we created the linked list. Where we can store data dynamically but main problem with linked list is that cost of accessing the data is O(n). You have to iterated the linked list from start to the your element to access the data.

Vectors (Dynamic Arrays)  in C++ Programming

Programmer of STL thinks that, can we create a new data structures which can access data in O(1) and We can also store data dynamically without declaring the size of the array. This is the reason for vectors existence in C++.

What are Vectors

Vectors are special type of class in STL library which have functionality of both arrays and linked list.It is a sequential container also known as dynamic arrays. It can store data in array dynamically and access element in O(1). There is no need to provide the size of the array at compile time because It’s size can grow and shrink dynamically according to our need. Let see few points of vectors before understanding it.

Properties of Vectors
  • Syntax for STL vectors is : std::vector<T> vec .
  • Std::vector is a sequence container and also known as Dynamic Array or Array List.
  • Vectors size can grow and shrink dynamically. There is no need to provide size at compile time.
  • Vectors have functions for accessing elements at(), [], front(), back(), data() .
  • Functions for modifying vector insert(), emplace(), push_back(), emplace_back(), pop_back(), resize(), swap(), erase(), clear() etc.

std::vector vec;

Here we have created an object of class vector with name vec.


Various operations on Vectors

std :: vector declaration

There are three ways to declare vectors in C++. We are going to see all of them one by one in this section.

std :: vector<int> vec;

Here we have declared an integer type of vector without initializing with any data.


std :: vector <int> vec (5,20);

We have created a vector of size 5 and initialized all elements of vector with 20.


std :: vector <int> vec = {1,2,3,4,5,6};

Here we directly stored data in vector as we stored in array.

Accessing the elements from a std :: vector

There are two ways of accessing elements from the vectors in C++. We are going to see all of them one by one in this section.

vec[3];
It returns the value at index three from the vector.If you go out of bound it will give you garbage value. That mean if you have let say 10 elements in your array than if try to access value from out of bound that it will return a garbage value.


vec.at(3) ;

It returns the value at index three from the vector.If you go out of bound it will give you an exception. That mean if you have let say 10 elements in your array than if try to access value from out of bound that it will give you exception.


vec.front() ;

It returns the first element of the vector.


vec.back() ;

It returns the last element of the vector.

std::vector Modifiers

In this section We are going to discuss all vectors modifiers that are available in C++ STL in details

1. vector :: push_back()

This function is used to add an element at end of the vector. It insert element at last in our array.

vec.push_back(12);
It inserted 12 at last of our array.


2. vector :: pop_back()

This is used to delete last elements from the vector.

vec.pop_back();
It removes the last element from our array.


3. vector :: swap()

This function is used to swap all content of two vectors of same types. Type of both vectors must be same for swapping the content.

std:: vector<int> v1={1,2,3};
std:: vector<int> v2={4,5,6};
v1.swap(v2);

It will swap all content of v1 with v2.


4. vector :: clear()

We use clear to delete all elements from the vector. It will make size of vector 0.

vec.clear();

It will delete all data of vector vec.


5. vector :: erase()

This function also delete data from your container. This function comes with an extra edge, here you can specify the range in between you want to delete data from your vector.You can also delete at a specific position.

1 vec.erase (position) ;
It will delete data of a specific index from your vector.

2. vec.erase(start,end);
It will delete all data withing range of start to end index.


6. vector :: resize()

This function is used to change the size of your vector.If given size is greater then actual size of vector then it add extra space in your vector. If given size is less then the actual size of vector it deletes the elements from your vector.

1 vec.resize(n);
It will make your vector’s size n;

2. vec.resize(n,val);
If size of your vector is less then n than It fill remaining value with the val in your vector.


7. vector :: insert()

We use this function to insert a value/object a particular position in vector.We pass the position and the value as parameter in the function. It is an inefficient way of doing it, because all member of vector reallocate their position for the insertion.

Vec.insert(pos,value);
It will insert value at particular index in your vector.

More Usefull std::vector functions

In this section We are going to discuss all various std :: vector function that can help us in writing more neat clean code.

1. vector :: data()

It return the pointer that is pointing to our vector/array. In other we can say it return the pointer to the first element of our vector.

int* p = vec.data();
Here p is pointing to the our arrays first element


2. vector :: capacity()

It returns the no of elements that can be inserted in our vector.

int c=vec.capacity();


3. vector :: size()

It returns no of elements that are currently present in our vector

int s= vec.size()


4. vector :: shrink_to_fit()

It removes extra spaces from our vector and decrease the capacity of the vector to the size of the vector.

vec.shrink_to_fit();

It will delete all data of vector vec.


5. vector :: reserve()

This function requests our compiler to reserve no of spaces for our vector. Or you can say we requests compiler to fix the minimum capacity for our vector. So class have not to do array creation again and again.

vec.reserve(300);

It will reserve 300 spots for storing the data in our vector object.


C++ pseudo code for vectors implementation

#include <iostream>
#include <vector>
int main(){
    
    //created vector
    std::vector<int> vec;
    // insertion from 0 to 99 in vector
    for(int i=0;i<99;++i){
        vec.push_back(i);
    }
    // printed the vector
    for(int i=0;i<vec.size();++i){
        std::cout<<vec.at(i)<<std::endl;
    }
    // deleted last element from the vector
    vec.pop_back();
    //inserted  123 at index : 20 in vector
    vec.insert(vec.begin()+20,123);
    // stores size of the vector in sz;
    int sz=vec.size();
    //stores capacity of vector in ca;
    int ca=vec.capacity();
    // It deleted the data from index 12 to 23 .. vec.begin points to the first element;
    vec.erase(vec.begin()+12,vec.begin()+23);
    // Now it deleted all data from the vector
    vec.clear();
    std::cin.get();
    
}

Subscribe to our YouTube channel

To get explanation of each and every article of coderca. Go on our official Youtube channel.Check it out from given link,


Best C++ books on Amazon

This Post Has 5 Comments

  1. Jesse Pie

    Simplest explanation of vectors on internet.
    Keep it up.
    You skills are better then my high school teacher.

  2. Animesh

    So how these things happening internally.I haven’t got it?

  3. Sanjay

    Crisp & clear !

Leave a Reply