Vectors in STL - C++ : Part - 1

Hello Coders, I welcome you all to learn this new topic that is a c++ vector. I’m sure that during your coding journey you all have used an array for storing the same type of data but while you are playing with an array there is a possibility that you might have got a segmentation fault error (accessing array index out of it's range). What if you have a similar data structure as an array but with more features.

Definition: Vectors are a sequence container that is a part of the C++ standard template library(STL). Vector uses contiguous storage locations for its elements. The basic difference between a vector and an array is vectors are dynamic arrays with the facility to resize itself whenever a new element is pushed inside the vector or deleted from a vector, unlike arrays that have predefined lengths.

In the standard template library, there is a template class known as vector. To declare any template object you have to mention datatype of that object inside <>.vector container is wrapped under vector library so to get benefits of the vector container you have to add the vector library in your program.

1. push_back(): This function is used to insert an element at the end of a vector and increments the size of a vector by one.

Input: vect={1,2,3,4,5,6}
Output: vect={1,2,3,4,5,6,10}

2. emplace_back(): This function is used to insert a new element into the vector container, the new element is added to the end of the vector.

This effectively increases the container size by one, which causes an automatic reallocation of memory if the size of a vector is greater than the current capacity of a vector

Input: vect={1,2,3,4,5,6}
Output: vect={1,2,3,4,5,6,10}

In vector elements are indexed from 0 to size() – 1. To access any element in vector by index vector provides two member functions i.e.

● at()

● operator[]

Let’s discuss them in detail,

Accessing elements of a vector using operator[]: It returns the reference of an element in the vector at index n. While accessing any element through operator [] we need to make sure that the given index is in the range i.e. less than the size of the vector, otherwise, it will result in undefined behavior and can also crash an application.

Accessing element using vector:: at(): It returns the reference of an element at index n in vector. If index n is out of range i.e. greater then the size of vector then it will throw out_of_range exception.

So that’s it for this article we will be coming up with our next article very soon till then keep learning, keep coding, keep reading and keep improving !!

Happy Coding 😊
By Programmers Army