Vector in C++

Video Tutorial
Datatypes in C++ thumbnail
This video belongs to
C++ Course: Learn the Essentials
14 modules

Vectors in C++ are one of the containers offered to us by the STL(Standard Template Library) in C++. It stores a collection of similar-type objects in a variable-sized array.

Note: C++ provides us with objects that store a collection of elements (i.e. other objects), referred to by the term ‘containers’.

Vector in C

Declaration of a vector in C++

In C++, a vector is a dynamic array, meaning that its size can grow or shrink as needed during program execution. Vectors are part of the C++ Standard Template Library (STL) and are declared using the following syntax:


  • std::vector is the namespace for vectors
  • <data_type> is the type of data the vector will store, such as int, double, or std::string
  • vector_name is the name of the vector

For example, to declare a vector of integers named numbers, you would write:

This vector can initially hold no elements, but its size can be increased or decreased as needed.

Initialization of a vector in C++

Initializing a vector in C++ involves assigning values to its elements. There are several ways to initialize a vector, including:

1. Using an initializer list:

An initializer list is a comma-separated list of values enclosed in curly braces. It is the simplest and most common way to initialize a vector.

This code initializes a vector named numbers with the values 1, 2, 3, 4, and 5.

2. Using the fill() algorithm:

The fill() algorithm fills all the elements of a vector with a specified value.

This code initializes a vector of 10 integer elements, all with the value 0.

3. Using a copy constructor:

A copy constructor creates a new vector by copying the values from an existing vector.

This code initializes a vector named numbers2 by copying the values of the vector numbers1.

4. Using an array:

An array can be used to initialize a vector.

This code initializes a vector named numbers using the elements of the array arr.

5. Using a range-based for loop:

A range-based for loop can be used to initialize a vector with values from another container.

This code initializes a vector named numbers by copying the values from the list values.

Basic Vector Operations

some of the basic vector operations in C++ are:

  1. Accessing Elements: You can access elements of a vector using either its index or an iterator. Indexing uses square brackets [] and an index value, while iterators provide a pointer-like interface to traverse the vector.
  1. Modifying Elements: You can modify the values of vector elements using either indexing or iterators. Both methods allow you to change the value at a specific position in the vector.
  1. Adding Elements: There are several ways to add new elements to a vector. The most common methods are using the push_back() and insert() functions.
  1. Removing Elements: You can remove elements from a vector using the erase() and pop_back() functions.
  1. Checking Size and Emptiness: The size() function returns the number of elements in the vector, while the empty() function checks whether the vector is empty or not.
  1. Resizing the Vector: You can resize a vector using the resize() function, which can either increase or decrease the vector's capacity.
  1. Clearing the Vector: The clear() function removes all elements from the vector, effectively emptying it.

Various Functions in Vectors


FunctionDescriptionExample Code
begin()Iterator to beginningauto it = a.begin();
end()Iterator to endauto it = a.end();
rbegin()Reverse iterator to reverse beginningauto rit = a.rbegin();
rend()Reverse iterator to reverse endauto rit = a.rend();
cbegin()Const_iterator to beginningauto cit = a.cbegin();
cend()Const_iterator to endauto cit = a.cend();
crbegin()Const_reverse_iterator to reverse beginningauto crit = a.crbegin();
crend()Const_reverse_iterator to reverse endauto crit = a.crend();

Example Code for Visualizing the use of Iterators:



FunctionDescriptionExample Code
size()Return sizesize_t size = a.size();
max_size()Return maximum sizesize_t maxSize = a.max_size();
resize(n)Change sizea.resize(10);
capacity()Return size of allocated storage capacitysize_t capacity = a.capacity();
empty()Test whether vector is emptybool isEmpty = a.empty();
reserve()Request a change in capacitya.reserve(100);
shrink_to_fit()Shrink to fita.shrink_to_fit();

Example Code for Visualizing the use of Capacity functions:



FunctionDescriptionExample Code
assign()Assign vector contenta.assign(4, 7);
push_back()Add element at the enda.push_back(10);
pop_back()Delete last elementa.pop_back();
insert()Insert elementsa.insert(a.begin(), 3);
erase()Erase elementsa.erase(a.begin());
swap()Swap contenta.swap(b);
clear()Clear contenta.clear();
emplace()Construct and insert elementa.emplace(a.begin(), 42);
emplace_back()Construct and insert element at the enda.emplace_back(42);

Example Code for Visualizing the use of Modifiers :


Element access:

FunctionDescriptionExample Code
operator[]Access elementint element = a[0];
at()Access element with bounds checkingint element =;
front()Access first elementint firstElement = a.front();
back()Access last elementint lastElement = a.back();
data()Access data as a pointerint* dataPtr =;

Example Code for Visualizing the use of Element access functions:


Allocators Function in Vector C++

Allocators are objects that manage the dynamic allocation and deallocation of memory for containers like vectors. In C++, vectors provide a single function called get_allocator() that allows you to access the allocator associated with a vector. This allocator can be used to allocate custom memory chunks or to modify the allocator's behavior.

When to use Vectors?

We can use Vectors in the following circumstances:

It is advisable to use vectors when data are consistently changing.

If the size of data is unknown then it is advisable to use vectors.

It is advisable to use vectors when elements are not predefined.

Compared to arrays there are more ways to copy vectors.

Vector of Vectors in C++ STL

In C++ STL, you can create a vector of vectors to represent a two-dimensional array or a matrix. This is often useful when dealing with a grid-like structure or a table. Here's an example of how to create and use a vector of vectors:


In this example:

  • std::vector<std::vector<int>> matrix; declares a vector of vectors of integers.
  • matrix.resize(rows); resizes the outer vector to the number of rows.
  • matrix[i].resize(columns); resizes each inner vector to the number of columns.
  • The matrix is then filled with values, and its elements are printed.

Advantages of Vectors

  • Dynamic Nature: Vectors can dynamically resize based on the number of elements.
  • Easy Insertion and Deletion: Elements can be easily inserted or deleted in vectors.
  • Storage of Multiple Objects: Vectors can store multiple objects of the same type.
  • Simple Copying: Copying vectors is straightforward using the assignment operator.

Disadvantages of Vectors

  • High Memory Consumption: Vectors may consume more memory compared to other data structures.
  • Lack of Direct Indexing: Vectors do not provide direct indexing, impacting random access efficiency.
  • Non-Contiguous Memory: The memory allocated for vectors may not be contiguous, affecting cache performance.


It can be concluded that vectors offer us a lot more than arrays and in order to excel in programming, one has to study the STL, especially the vector class.

Reasons for such an abundant usage of vectors are as follows :

  • Dynamic nature (the size of a vector can be adjusted accordingly).
  • Since vectors offer us dynamic arrays. We are able to have unique-sized arrays even in multidimensional arrays.
  • There are multiple ways to copy one vector to another.
  • Easy to pass as an argument.
  • Easy initialisation with constant values.
  • Multiple member functions for user's convenience.
  • Easy to clear the vector for saving memory.

A vector is always a better option over arrays and linked lists in storing and managing bulky and dynamic data in our program.

Read More: