C++ Vector | Learn 5 Types of Functions Associated with Vector

A vector in C++ is one of the most basic concepts of its Standard Template Library. Programming in C++ is incomplete without possessing the knowledge of vectors. C++ Vectors are nothing but arrays that are dynamic in nature which means that vectors possess the ability to change their size anytime during program run.

Before we begin, it is important to have a basic idea of Arrays in C/C++.

C++ Vectors Tutorial

C++ Vector

Vectors are basically a data structure that not only acts as a dynamic array but also ensures quick and random access of elements pertaining to that vector.

We can easily insert, delete, traverse, and modify elements as well as manage computer memory required to store these with the help of the C++ sequence container.

Just like arrays, vectors are stored in contiguous memory locations for easy traversal with the help of iteration.

Note: It is important to note that Vector in C++ is totally different from Vectors in mathematics.

Key takeaway: We need to include the header file #include<vector> in order to access the Standard Template Library functions associated with vectors.

Vectors in C++

Let us first discuss the basic syntax and the components of vectors before moving on to a C++ program.

Definition

Here is a definition of std::vector

template < class T, class Alloc = allocator<T> > class vector;

Now, let us discuss each component:

  • template – We have already discussed C++ templates in detail in our previous tutorial.
  • class – A keyword with goes along with templates.
  • T – It indicates the type of element contained in the vector.
  • Alloc – It denotes the type of allocator object.

C++ Vectors Example

In order to acquaint ourselves with vectors, let us consider a very simple program to insert elements into the vector in C++:

#include <iostream> 
#include <vector> 
using namespace std;

int main() 
{

vector <string> v;

v.push_back("Welcome "); 
v.push_back("to "); 
v.push_back("DataFlair "); 
v.push_back("tutorials! ");

for(vector<string>::iterator i=v.begin();i!=v.end();++i) 
cout<<*i; 
return 0; 
}

Code-

Vectors in C++ with Example

Output-

Output of Vectors in C++

Importance of C++ Vector

Unlike arrays, vectors are dynamic in nature that helps in efficient memory management.

Moreover, there are several member functions associated with vectors that help you ease out your way in manipulation and modification operations like insertion, deletion, traversal from the beginning, end, or middle of the vector.

Another advantage of vectors over arrays is that we create a dynamic array, we need to explicitly deallocate memory whereas, in a vector, the memory is automatically deallocated in the heap memory.

Unveil the Important Concepts – Multi-dimensional Arrays in C/C++ (2D & 3D Arrays)

Data Manipulation Operations on C++ Vector

As discussed earlier, it is pretty easy to perform data manipulation operations on Vectors.

Let us now discuss functions associated to perform different operations and the time taken by them:

  1. Insertion: Normally, if we want to insert an element into the vector, it is done from its rear end. We need to use the v.back() function in order to insert an element in the vector. This operation consumes differential time as there may be a need for extending the vector. If we wish to insert an element at the beginning or in the middle, it takes linear time.
  2. Deletion: Normally, if we talk about deleting an element from the vector, we do it from the rear end. We need to use the v.pop_back() function to delete an element from the rear end. It takes constant time as it is evident that no resizing of the vector takes place. If we wish to delete an element at the beginning or in the middle, it takes linear time.

Functions Correlated to C++ Vector

When we talk about member functions of vectors, there are basically 5 categories of functions associated with C++ vectors. The major operations on vectors are based on iteration, capacity, element access control, and modifiers.

On the other hand, when talking about non-member functions, there are only 2 vector functions available in the Standard Template Library.

Enhance your fundamental skills with Functions in C/C++ 

Types of Function Correlated to Vectors

  1. Iterator Functions
  2. Capacity Control Functions
  3. Element Access Control Functions
  4. Modifier Functions
  5. Allocator Functions

1. Iterator Functions

  • begin(): The begin() function would return an iterator pointing to the beginning element of the C++ vector.
  • cbegin(): The cbegin() function would return a constant iterator to the beginning element of the vector.
  • cend(): The cend() functions would return a constant pointer to the general element that follows the end element of the vector.
  • crbegin(): The crbegin() function would return a constant reverse iterator pointing to the end element in the vector, that is, from the last element to the first element (reverse order).
  • crend(): The crend() function would return a constant reverse iterator pointing to the general element preceding the first element in the vector.
  • end(): The end() functions would return a pointer to the general element that follows the end element of the vector.
  • rbegin(): The rbegin() function would return a reverse iterator pointing to the end element in the vector, that is, from the last element to the first element (reverse order).
  • rend(): The rend() function would return a reverse iterator pointing to the general element preceding the first element in the vector in C++.

Example of Iterator Function in C++

Here is a C++ program that illustrates the use of these iterator functions:

#include <iostream> 
#include <vector> 
using namespace std; 

int main() 
{

cout<<"Welcome to DataFlair tutorials!"<<endl<<endl;

vector<int> v; 

for (int i = 1; i <= 10; i++) // Inserting elements from 10 to 20 in the vector
v.push_back(i); 

cout<<"Using begin() and end(): "; 
for (auto i = v.begin(); i != v.end(); ++i) 
cout<< *i << "\t"; 

cout<<endl<<"Using cbegin() and cend(): "; 
for (auto i = v.cbegin(); i != v.cend(); ++i) 
cout<< *i << "\t";

// Reversal operations 
cout<<endl<<"Using rbegin() and rend(): "; 
for (auto j = v.rbegin(); j != v.rend(); ++j) 
cout << *j << "\t"; 

cout<<endl<<"Using crbegin() and crend(): "; 
for (auto j = v.crbegin(); j != v.crend(); ++j) 
cout << *j << "\t"; 

return 0; 
}

Code-

Example to Use Iterator functions in Cpp

Output-

Output of Iterator functions in C++

2. Capacity Control Functions

  • capacity(): The capacity() function would return the storage space size of the currently allocated vector expressed as the number of elements.
  • empty(): The empty() function would return true if the container is empty or not.
  • max_size(): The max_size() function would return the maximum number of elements that the vector can hold.
  • reserve(): The reserve() function would request the C++ compiler that the vector capacity is at least enough to contain n1 number of elements.
  • resize(): The resize() function would resize the container so that it contains ‘n2’ number of elements.
  • shrink_to_fit(): The shrink_to_fit() function would reduce the capacity of the container to fit its size. Along with that, this function even destroys all elements beyond the capacity of the vector.
  • size(): The size() function would return the number of elements in the vector in C++.

Have you learned Virtual Function in C++?

Example of Capacity Control Function in C++

Here is a C++ program that illustrates the use of these capacity control functions:

#include <iostream> 
#include <vector> 
using namespace std; 

int main() 
{

cout<<"Welcome to DataFlair tutorials!"<<endl<<endl;

vector<int> v; 

for (int i = 1; i <= 10; i++) 
v.push_back(i);

// Function to find the capacity of the vector
cout<<endl<<"The capacity of the vector is: " << v.capacity();

// Conditional statement to check if the vector is empty or not 
if (v.empty() == false) 
cout<<endl<<"The vector is not empty "<<endl;
else
cout<<endl<<"The vector is empty "<<endl; 
cout << "Size : " << v.size(); 

// Function to find the max size of the vector 
cout<<endl<<"The max size of the vector is: " << v.max_size(); 

// Function to resize the vector size to 5 
v.resize(5); 

// Function to print the vector size after using resize() 
cout<<endl<<"The size of the vector is: " << v.size(); 

// Function to shrink the vector 
v.shrink_to_fit(); 
cout<<endl<<"The elements in the Vector are: "; 
for (auto j = v.begin(); j != v.end(); j++) 
cout << *j << "\t"; 

return 0; 
}

Code-

Example of Capacity Control Function in C++

Output-

Output of Capacity Control Function in C++

3. Element Access Control Functions

  • at(n): The at(n) function would return a reference to the element at position ‘nth’ in the C++ vector.
  • back(): The back() function would return a reference to the last element in the vector.
  • data(): The data() function would return a direct pointer to the memory array used internally by the vector to store its owned elements.
  • front() : The front() function would returns a reference to the first element in the vector.
  • [n]: The [n] operator is called the reference operator in which ‘n’ is the position of an element in the vector. This operator would return a reference to the element at the ‘nth’ position.

An Important Ingredient for a successful Programmer is Inline Function in C++

Example of Element Access Control Function in C++

Here is a C++ program that illustrates the use of these element access control functions:

#include <iostream>
#include <bits/stdc++.h> 
using namespace std; 

int main() 
{

cout<<"Welcome to DataFlair tutorials!"<<endl<<endl;

vector<int> v; 

for (int i = 1; i <= 10; i++) // Inserting elements 10, 20, 30, ..... , 100
v.push_back(i * 10); 

cout<<endl<<"Using the Reference operator [n] : n1[5] = " << v[5]; 

cout<<endl<<"Using the at(n) function : at(3) = " << v.at(3); 

cout<<endl<<"Using the front() function : front() = " << v.front(); 

cout<<endl<<"Using the back() function: back() = " << v.back(); 


int* position = v.data(); // Pointer to the first element 

cout<<endl<<"The first element of the vector is " << *position <<endl;
return 0; 
}

Code-

Example of Element Access Control Function in C++

Output-

Output of Element Access Control Function in C++

4. Modifier Functions

  • assign(): The assign operator would assign a new value to the vector elements by replacing old ones.
  • clear(): The clear() function would remove all the elements of the vector container.
  • emplace(): The emplace() function would extend the container by inserting a new element at the position.
  • emplace_back(): The emplace_back() function would insert a new element into the vector container, the new element is added to the end of the vector.
  • erase(): The erase() function would remove elements from a container from the specified position or range.
  • insert(): The insert() function would insert new elements before the element at the specified position
  • pop_back(): The pop_back() function would pop or remove elements from a vector from the back.
  • push_back(): The push_back() function would push the elements into a vector from the back.
  • swap(): The swap() function would swap the contents of one vector with another vector of the same type. By using this function, the sizes may differ.

Example of Modifier Function in C++

Here is a C++ program that illustrates the use of these modifier functions:

#include <iostream>
#include <bits/stdc++.h> 
#include <vector> 
using namespace std; 

int main() 
{

cout<<"Welcome to DataFlair tutorials!"<<endl<<endl;

vector<int> v; 

v.assign(5, 2); // Inserting the element "2" five times in the vector

cout<<"The elements in the vector are: "; 
for(int i = 0; i < v.size(); i++) 
cout << v[i] << "\t"; 

v.push_back(32); // Inserting the element "32" at the last position
int n = v.size(); 
cout<<endl<<"The last element of the vector is: " << v[n - 1];

v.pop_back(); // Removing the last element of the vector

// Displaying the elements of the vector 
cout<<endl<<"The vector elements are: "; 
for(int i = 0; i < v.size(); i++) 
cout << v[i] << "\t"; 

v.insert(v.begin(), 64); // Inserting "64" at the front in the vector

cout<<endl<<"The first element of the vector is: " << v[0]; 

v.erase(v.begin()); // Removing the first element from the vector

cout<<endl<<"The first element of the vector is: " << v[0]; 

v.emplace(v.begin(), 32); // Inserting element at the beginning of the vector
cout<<endl<<"The first element of the vector is: " << v[0]; 


v.emplace_back(30); // Inserting "30" at the end of the vector
n = v.size(); 
cout<<endl<<"The last element of the vector is: " << v[n - 1]; 

v.clear(); // Erasing the vector 
cout<<endl<<"The size of the vector after erasing is: " << v.size(); 

// Swapping vectors 
vector<int> v1, v2; 
v1.push_back(100); 
v1.push_back(200); 
v2.push_back(300); 
v2.push_back(400); 

cout<<endl<<"The first vector is : "; 
for (int i = 0; i < v1.size(); i++) 
cout << v1[i] << "\t"; 

cout<<endl<<"The second vector is : "; 
for (int i = 0; i < v2.size(); i++) 
cout << v2[i] << "\t"; 

// Swapping v1 with v2 
v1.swap(v2); 

cout<<endl<<"After swapping the first Vector: "; 
for (int i = 0; i < v1.size(); i++) 
cout << v1[i] << "\t"; 

cout<<endl<<"After swapping the second Vector 2: "; 
for (int i = 0; i < v2.size(); i++) 
cout << v2[i] << "\t";

return 0;
}

Output-

Output of Modifier Function in C++

5. Allocator Functions

In the C++ Standard Template Library, sequence containers can change size dynamically. An allocator is basically an object that is responsible for dynamic memory allocation and deallocation.

In C++ vectors, there is only one function to achieve this task. This function is called the get_allocator() function. We use the get_allocator() to allocate chunks of memory which returns a copy of the allocator object associated with the container.

Summary

As we learned C++ vectors are a data structure that not only acts as a dynamic array but also ensures quick and random access of elements pertaining to that vector. Now, you can easily insert, delete, traverse, and modify elements as well as manage computer memory. Vectors are an important concept for every C++ professional.

Get ready to Explore Function and Operator Overloading in C++ and become an expert in 7 Min

Suggestions and feedback are welcomed in the comment section!

Leave a Reply

Your email address will not be published. Required fields are marked *

This site is protected by reCAPTCHA and the Google Privacy Policy and Terms of Service apply.