Vector in STL
What is a vector?
Standard Template Library (STL) has 3 components:
· Containers
· Algorithms
· Iterators
Vector is a sequence container that stores data in memory into an organized fashion. It is implemented by template class and therefore can be easily modified and customized to hold different types of data. Vector can be defined as dynamic array which permits direct access to any element. To implement a vector, we need to include a header file, namely :
#include<vector>
Vector syntax :
vector<data_type>vector_name;
There are some functions which are performed on vectors.
Those functions are :
· vector_name.begin() : It returns an iterator element which points to first element of vector.
· vector_name.end() : It returns an iterator element which points to last element of vector.
· vector_name.push_back(value) : This function insert the given element into the vector from the end.
· vector_name.pop_back() : This function deletes the element from the end of the vector.
· vector_name.swap(vector_name2) : It swaps the two input vectors.
· vector_name.size() : It returns the size of the vector i.e. provide the number of elements present in the vector.
· vector_name.insert(position, value) : This function adds the element before the element at the given location/position.
· vector_name.empty() : Checks whether the vector is empty or not and returns a Boolean value.
· vector_name.front() : It returns the first element of the vector.
· vector_name.back() : It returns the last element of the vector.
· vector_name.erase(vector_name.begin()+i) : Delete or erase a particular element at the given index.
There are more functions which can be applied on vectors but the above mentioned functions are the most common and widely used.
Iterate over a vector using iterator :
· As vector_name.begin() and vector_name.end() returns a pointer that points the start and end of the vector respectively, so, we can print the element using *. i.e.
vector <int> v {1,2,3,4,5};
for(int i=v.begin() ; i!=v.end() ; i++)
{ cout<<*it ; }
· Like array, you can also indices to print the elements. i.e.
vector <int> v {1,2,3,4,5};
for(int i=0 ; i<v.size() ; i++)
{ cout<<v[i] ;}
The more you explore, the more you learn.
So, give it a read and if you like this then don’t forget to give a clap.