In this article we are going to see about vector
in C++.
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:
Where,
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:
Where,
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.
Array
is not automatically de-allocated where vector
is 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; vector<int> myvector; 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<<arr[i]; for(int i=0;i<5;i++) cout<<myvector[i]; |
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
Vector STL in C++
STL
is the strength of CPP. Programmers often prefers CPP to implement data structures for its STL. Vector has several STL functions which are listed below. Before going through those functions, it’s worth mentioning that vector
can be seen as container and we can access vector elements with help of iterators. An iterator
is a similar thing like pointer
. Below is an example where vector is access by iterator instead of indexing (previously explained).
|
//declare iterator vector<int>:: iterator it; for(it=myvector.begin();it!=myvector.end();it++){ cout<<*it<<endl; //acessing elements } |
The STL functions widely used are,
Iterator related
.begin()
: points to beginning of the vector(first element)
.end()
: points to end of the vector, for understanding after the last element of the vector
.rbegin()
: points to last element of the vector(for reverse traversal)
.rend()
: points to start of the vector, for understanding before the first element of the vector
All of the above returns the iterator pointing to the above-specified positions. Example is the following:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42
|
#include <bits/stdc++.h> using namespace std; int main(){ //declare vector vector<int> myvector; //create the vector int n,item; cout<<"Input number of elements (initially)"; cin>>n; cout<<"Input elements\n"; while(n--){ cin>>item; myvector.push_back(item); } //if you want you can add more addding some code snippet for more input //iterating vector elements with help of function .begin() and .end() cout<<"starting element: "<<*(myvector.begin())<<endl; cout<<"iterating in forward direction\n"; vector<int> :: iterator it; //another way is to use auto in the loop used next time for(it=myvector.begin();it!=myvector.end();it++){ cout<<"element: "<<*it<<endl; } //iterating vector elements in reverse direction with help of function .rbegin() and .rend() cout<<"iterating in reverse direction\n"; for(auto ij=myvector.rbegin();ij!=myvector.rend();ij++){ //if you use it here, it will show error , either auto new_name or it cout<<"element: "<<*ij<<endl; } return 0; } |
Input number of elements (initially)5
Input elements
2 4 6 8 10
starting element: 2
iterating in forward direction
element: 2
element: 4
element: 6
element: 8
element: 10
iterating in reverse direction
element: 10
element: 8
element: 6
element: 4
element: 2
Insertion-deletion related
.push_back(item)
: pushes a new item at the end.
.insert(iterator it , item)
: inserts item before the specified position it
.pop_back()
: removes an element from the back.
.erase(iterator it)
: removes element from specified position it
.clear()
: removes all elements from vector
Example of the above is following:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63
|
#include <bits/stdc++.h> using namespace std; int main(){ //declare vector vector<int> myvector; vector<int>::iterator it; //create the vector int n,item; cout<<"Input number of elements (initially)"; cin>>n; cout<<"Input elements\n"; //1.use of push_back while(n--){ cin>>item; myvector.push_back(item); } //2.use of insert() cout<<"Enter value to insert\n"; cin>>item; cout<<"inserting at the begining\n"; myvector.insert(myvector.begin(),item); //it=myvector.begin() cout<<"After insertion:\n"; for(it=myvector.begin();it!=myvector.end();it++){ cout<<"element: "<<*it<<endl; } //3.use of pop_back() cout<<"Popping the last element:\n"; myvector.pop_back(); cout<<"After Popping\n"; for(it=myvector.begin();it!=myvector.end();it++){ cout<<"element: "<<*it<<endl; } //4.use of ersae() cout<<"erasing the first element\n"; myvector.erase(myvector.begin()); cout<<"New first element is : "<<*myvector.begin()<<endl; //use of clear() myvector.clear(); cout<<"After clearing\n"; cout<<"Size of vector: "<<myvector.size()<<endl; return 0; } |
Input number of elements (initially)7
Input elements
2 3 4 5 7 8 9
Enter value to insert
1
inserting at the begining
After insertion:
element: 1
element: 2
element: 3
element: 4
element: 5
element: 7
element: 8
element: 9
Popping the last element:
After Popping
element: 1
element: 2
element: 3
element: 4
element: 5
element: 7
element: 8
erasing the first element
New first element is : 2
After clearing
Size of vector: 0
Accessing the elements related
at(int pos)
: returns reference of element at position pos
front(): returns reference of first element
back(): returns reference of last element
Example of the above is following:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37
|
#include <bits/stdc++.h> using namespace std; int main(){ //declare vector vector<int> myvector; vector<int>::iterator it; //create the vector int n,item; cout<<"Input number of elements (initially)\n"; cin>>n; cout<<"Input elements\n"; while(n--){ cin>>item; myvector.push_back(item); } //1.use of at() int index; cout<<"Enter value of valid index\n"; cin>>index; cout<<"value at index "<<index<<" is: "<<myvector.at(index)<<endl; //2.use of front() cout<<"the front element is: "<<myvector.front()<<endl; //3.use of back() cout<<"the last element is: "<<myvector.back()<<endl; return 0; } |
Input number of elements (initially)
5
Input elements
3 4 5 6 8
Enter value of valid index
3
value at index 3 is: 6
the front element is: 3
the last element is: 8
Size related
.size()
: returns current size of vector
.max_size()
: returns maximum size possible for the vector
.empty()
: Boolean function, returns whether vector is empty or not
Example of the above is following:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42
|
#include <bits/stdc++.h> using namespace std; int main(){ //declare vector vector<int> myvector; vector<int>::iterator it; //create the vector int n,item; cout<<"Input number of elements (initially)\n"; cin>>n; cout<<"Input elements\n"; while(n--){ cin>>item; myvector.push_back(item); } //1.use of size() cout<<"size of the vector is "<<myvector.size()<<endl; //2.use of max_size() cout<<"maximum size of the vector can be "<<myvector.max_size()<<endl; //3.use of emepty() //returns true if vector is empty else false while(!myvector.empty()){ cout<<"size of vector: "<<myvector.size()<<endl; myvector.pop_back(); } if(myvector.empty()) cout<<"Vector is empty now\n"; return 0; } |
Input number of elements (initially)
6
Input elements
3 4 5 6 7 8
size of the vector is 6
maximum size of the vector can be 4611686018427387903
size of vector: 6
size of vector: 5
size of vector: 4
size of vector: 3
size of vector: 2
size of vector: 1
Vector is empty now
Some other useful functions
sort()
sorting is basic algorithm we know. Vector can be easily sorted by
the following function.
|
//in ascending order sort(myvector.begin(),myvector.end()) //in descending order sort(myvector.begin(),myvector.end(),greater<int>()); |
find min/max element in vector
You can use following std function to find max and min elements in the vector.
|
// Find max *(std::max_element(myvector.begin(),myvector.end())) // Find min *(std::min_element(myvector.begin(),myvector.end())) |
Example of the above is following:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53
|
#include <bits/stdc++.h> using namespace std; int main(){ //declare vector vector<int> myvector; vector<int>::iterator it; //create the vector int n,item; cout<<"Input number of elements (initially)\n"; cin>>n; cout<<"Input elements\n"; while(n--){ cin>>item; myvector.push_back(item); } //1.sorting in ascending order cout<<"sorting in ascending order\n"; sort(myvector.begin(),myvector.end()); cout<<"After sorting\n"; for(auto it=myvector.begin();it!=myvector.end();it++){ cout<<*it<<" "; } cout<<endl; //2.sorting in descending order cout<<"sorting in descending order\n"; sort(myvector.begin(),myvector.end(),greater<int>()); cout<<"After sorting in descending order\n"; for(auto it=myvector.begin();it!=myvector.end();it++){ cout<<*it<<" "; } cout<<endl; //3.finding max() cout<<"The maximum element is: "<<*(std::max_element(myvector.begin(),myvector.end()))<<endl; //4.finding min() cout<<"The minimum element is: "<<*(std::min_element(myvector.begin(),myvector.end()))<<endl; return 0; } |
Input number of elements (initially)
5
Input elements
4 2 3 6 7
sorting in ascending order
After sorting
2 3 4 6 7
sorting in descending order
After sorting in descending order
7 6 4 3 2
The maximum element is: 7
The minimum element is: 2
That’s all for vector in C++. Definitely vector in very strong linear data struct and very easy to use. In our next section we would learn about vector of vectors which can be thought of 2D array in C/C++.
Let us know if this post was helpful. Feedbacks are monitored on daily basis. Please do provide feedback as that\'s the only way to improve.