In this article we are going to see about vector in C++.
[toc]
What is vector?
Those who are similar to C, can think vector as an array. The usage of vector is quite similar to array. But vector has certain advantages over array. Normally, an array is static in nature both in C or C++.
We declare a static array as:
Type_t array[size];
Type_t =any data type like int/float/char etc.
array =array name
size =static size of array
So, typically, static array is restricted by its predefined size. But, vector is dynamic in nature.
In CPP, we have the feature of vector which can be supplementary of array with additional privileges. Vector is not restricted by size, dynamic in nature. We declare a vector like:
vectormyvector;
Type_t=any data type like int/float/char etc.
myvector =vector name
Array vs Vector in C++
- Size of array is fixed where vector is resizable. It can shrink, it can grow as per program flow.
Arrayis not automatically de-allocated wherevectoris automatically de-allocated.- Arrays can’t be returned from a function (if not dynamically allotted), can’t be copied to another array. But same operations are valid for vector.
So, from the above comparison, vector is a better option when we are not sure about the size of array.
Functions in vector
Continuing the above comparison, let’s check the functionalities of array implemented in vector. Then we will check additional STL functions for vector.
Inserting elements in the array/vector
Let’s create an array of 5 integer first. Then try to add more integers. If we use array then
//code snippet to insert five elements to array
int arr[5];
for(int i=0;i<5;i++){
cin>>arr[i];
}
Now to insert more element, we need to create new array and copy the previous elements and then start adding. Such a tedious job!!
Using vector,
int item; vectormyvector; for(int i=0;i<5;i++){ cin>>item; myvector.push_back(item); }
To add more items, simple take input and push_back
in some loop cin>>item myvector.push_back(item)
No worry about the growing size of vector
Remember,
cin>>arr[i] works perfect but never try cin>>myvector[i] (Or you can try try and check once ☺)
arr[i] refers to some memory, myvector[i] doesn’t.
Accessing elements in the array/vector
The accessing process is same for both array and vector which is by indexing. Both uses 0 indexing and for valid indexing returns the indexed element. Access time is O(1). Continuing the above example,
for(int i=0;i<5;i++) cout<Above was the basic demonstration of vector. Till now we have mainly compared with array and similar features. Now, we will focus on vector as part of STL
Further reading: