In C++, vector is a dynamic array with the ability to resize itself automatically when an element is inserted or deleted. It is the part Standard Template Library (STL) and provide various useful functions for data manipulation.
Let’s take a look a simple example to demonstrate the use of vector container:
C++
#include <bits/stdc++.h>
using namespace std;
int main() {
// Creating a vector of 5 elements
vector<int> v = {1, 4, 2, 3, 5};
for (int i = 0; i < v.size(); i++) {
cout << v[i] << " ";
}
return 0;
}
Syntax of Vector
Vector is defined as the std::vector class template which contains its implementation and some useful member functions. It is defined inside the <vector> header file.
vector<T> vec_name;
where,
- T: Type of elements in the vector.
- vec_name: Name assigned to the vector.
To master vectors and other STL components, check out our Complete C++ Course, which covers the ins and outs of C++ STL with real-world examples and hands-on projects.
Declaration and Initialization
Declaration and initialization are the process of creating an instance of std::vector class and assigning it some initial value. In C++, vectors can be declared and initialized in multiple ways as shown below:
1. Default Initialization
An empty vector can be created using the below declaration. This vector can be filled later on in the program.
vector<T> vec_name;
2. Initialization with Size and Default Value
A vector of a specific size can also be declared and initialized to the given value as default value.
vector<T> vec_name(size, value);
3. Initialization Using Initializer List
Vector can also be initialized using a list of values enclosed in {} braces separated by comma.
vector<T> vec_name = { v1, v2, v3….};
vector<T> vec_name ({ v1, v2, v3….});
Let’s take a look at an example that shows implements the above methods:
C++
#include <bits/stdc++.h>
using namespace std;
void printV(vector<int> &v) {
for (int i = 0; i < v.size(); i++) {
cout << v[i] << " ";
}
cout << endl;
}
int main() {
// Creating an empty vector
vector<int> v1;
// Creating a vector of 5 elements from
// initializer list
vector<int> v2 = {1, 4, 2, 3, 5};
// Creating a vector of 5 elements with
// default value
vector<int> v3(5, 9);
printV(v1);
printV(v2);
printV(v3);
return 0;
}
Output1 4 2 3 5
9 9 9 9 9
More ways to declare and initialize vectors are discussed in this article – 8 Ways to Initialize Vector in C++
Basic Vector Operations
The basic operations of vector are shown below:
1. Accessing Elements
Just like arrays, vector elements can be accessed using their index inside the [] subscript operator. This method is fast but doesn’t check whether the given index exists in the vector or not. So, there is another member method vector at() for safely accessing elements:
The below example illustrates how to access the vector elements:
C++
#include <bits/stdc++.h>
using namespace std;
int main() {
vector<char> v = {'a', 'c', 'f', 'd', 'z'};
// Accessing and printing values using indexes
cout << v[3] << endl;
cout << v.at(2);
return 0;
}
To know more about accessing vector elements, refer to the article – How to Access an Element in a Vector in C++?
2. Updating Elements
Updating elements is very similar to the accessing except that we use an additional assignment operator to assign a new value to a particular element. It uses the same methods: [] subscript operator and vector at().
The below example illustrates how to update vector elements:
C++
#include <bits/stdc++.h>
using namespace std;
int main() {
vector<char> v = {'a', 'c', 'f', 'd', 'z'};
// Updating values using indexes 3 and 2
v[3] = 'D';
v.at(2) = 'F';
cout << v[3] << endl;
cout << v.at(2);
return 0;
}
More methods to update vector elements are discussed in this article – How to Update Vector Elements in C++?
3. Traversing Vector
Vector in C++ can be traversed using indexes in a loop. The indexes start from 0 and go up to vector size – 1. To iterate through this range, we can use a loop and determine the size of the vector using the vector size() method.
C++
#include <bits/stdc++.h>
using namespace std;
int main() {
vector<char> v = {'a', 'c', 'f', 'd', 'z'};
// Traversing vector using vector size()
for (int i = 0; i < v.size(); i++) {
cout << v[i] << " ";
}
return 0;
}
Outputa c f d z
a c f d z
More ways to traverse vectors are discussed in this article – How to Iterate Through a Vector in C++?
4. Inserting Elements
An element can be inserted into a vector using vector insert() method which takes linear time. But for the insertion at the end, the vector push_back() method can be used. It is much faster, taking only constant time.
The below example illustrates how to insert elements in the vector:
C++
#include <bits/stdc++.h>
using namespace std;
int main() {
vector<char> v = {'a', 'f', 'd'};
// Inserting 'z' at the back
v.push_back('z');
// Inserting 'c' at index 1
v.insert(v.begin() + 1, 'c');
for (int i = 0; i < v.size(); i++) {
cout << v[i] << " ";
}
return 0;
}
More ways to insert an element in the vector are discussed in this article – How to Add Elements in a Vector in C++?
5. Deleting Elements
An element can be deleted from a vector using vector erase() but this method needs iterator to the element to be deleted. If only the value of the element is known, then find() function is used to find the position of this element.
For the deletion at the end, the vector pop_back() method can be used, and it is much faster, taking only constant time.
The below example demonstrates how to delete an element from the vector:
C++
#include <bits/stdc++.h>
using namespace std;
int main() {
vector<char> v = {'a', 'c', 'f', 'd', 'z'};
// Deleting last element 'z'
v.pop_back();
for (int i = 0; i < v.size(); i++) {
cout << v[i] << " ";
}
cout << endl;
// Deleting element 'f'
v.erase(find(v.begin(), v.end(), 'f'));
for (int i = 0; i < v.size(); i++) {
cout << v[i] << " ";
}
return 0;
}
To know more about the deletion of an element in the vector, refer to this article – How to Remove an Element from Vector in C++?
Other Common Operations on Vector
Vector is one of the most frequently used containers in C++. It is used in many situations for different purposes. The following examples aim to help you master vector operations beyond the basics.
Passing Vector to Functions
Vectors can be passed to a function as arguments just like any other variable in C++. But it is recommended to pass the vector by reference so as to avoid the copying of all elements which can be expensive if the vector is large. Refer to this article to know more – Passing Vector to a Function
Internal Working of Vector
Vector internal working is very interesting and useful to select and optimize its usage. Understanding the internal memory management also helps in modifying the default mechanism of vector to suits our needs. Refer to this article to know more – Internal Working of Vector
Multidimensional Vectors in C++
Just like arrays, we can also create multidimensional vectors in C++. Each element of multidimensional vector can be visualized as the collection of vectors with dimension one less that the current vector. For example, 2D vectors are the collection of 1D vectors, while 3D vectors are the collection of 2D vectors and so on.
With the addition of each dimension, the complexity of operations on the vectors also increases.
Refer to this article to know more – Multidimensional Vectors in C++
All Member Functions of Vector
Following is the list of all member functions of std::vector class in C++:
Vector Function
| Description
|
|---|
push_back()
| Adds an element to the end of the vector. |
|---|
pop_back()
| Removes the last element of the vector. |
|---|
size()
| Returns the number of elements in the vector. |
|---|
max_size()
| Returns the maximum number of elements that the vector can hold. |
|---|
resize()
| Changes the size of the vector. |
|---|
empty()
| Checks if the vector is empty. |
|---|
operator[]
| Accesses the element at a specific position. |
|---|
at()
| Accesses the element at a specific position, with bounds checking. |
|---|
front()
| Accesses the first element of the vector. |
|---|
back()
| Accesses the last element of the vector. |
|---|
begin()
| Returns an iterator pointing to the first element of the vector. |
|---|
end()
| Returns an iterator pointing to the past-the-end element of the vector. |
|---|
rbegin()
| Returns a reverse iterator pointing to the last element of the vector. |
|---|
rend()
| Returns a reverse iterator pointing to the element preceding the first element of the vector. |
|---|
cbegin
| Returns const_iterator to beginning |
|---|
cend
| Returns const_iterator to end |
|---|
crbegin
| Returns const_reverse_iterator to reverse beginning |
|---|
crend
| Returns const_reverse_iterator to reverse end |
|---|
insert()
| Inserts elements at a specific position in the vector. |
|---|
erase()
| Removes elements from a specific position or range in the vector. |
|---|
swap()
| Swaps the contents of the vector with those of another vector. |
|---|
clear()
| Removes all elements from the vector. |
|---|
emplace()
| Constructs and inserts an element in the vector. |
|---|
emplace_back()
| Constructs and inserts an element at the end of the vector. |
|---|
assign()
| Assigns new values to the vector elements by replacing old ones. |
|---|
capacity()
| Returns the size of the storage space currently allocated to the vector. |
|---|
reserve()
| Requests that the vector capacity be at least enough to contain a specified number of elements. |
|---|
shrink_to_fit()
| Reduces memory usage by freeing unused space. |
|---|
data()
| Returns a direct pointer to the memory array used internally by the vector to store its owned elements. |
|---|
get_allocator
| Returns a copy of the allocator object associated with the vector. |
|---|
Similar Reads
Vector in C++ STL
In C++, vector is a dynamic array with the ability to resize itself automatically when an element is inserted or deleted. It is the part Standard Template Library (STL) and provide various useful functions for data manipulation. Let's take a look a simple example to demonstrate the use of vector con
9 min read
8 Ways to Initialize Vector in C++
Initializing a vector means assigning some initial values to the std::vector elements. In this article, we will learn 8 different ways to initialize a vector in C++. Table of Content Using Initializer ListOne by One InitializationWith a Single ValueFrom an ArrayFrom Another VectorFrom Any STL Contai
5 min read
Commonly Used Methods
Vector end() in C++ STL
In C++, the vector end() is a built-in method used to obtain an iterator pointing to the theoretical element after the last element of the vector. Even though this iterator does not point to a valid element, it serves as a marker for the end of the vector. Let’s take a look at an example that illust
4 min read
Vector empty() in C++ STL
In C++, vector empty() is a built-in method used to check whether the given vector is empty or not. In this article, we will learn about vector empty() method in C++. Let’s take a look at an example that illustrates the vector empty() method: [GFGTABS] C++ #include <bits/stdc++.h> using namesp
2 min read
Vector operator[ ] in C++ STL
In C++, the vector operator [] is used to randomly access or update the elements of vector using their indexes. It is similar to the vector at() function but it doesn't check whether the given index lies in the vector or not. Let’s take a look at a simple code example: [GFGTABS] C++ #include <bit
3 min read
Vector front() in C++ STL
In C++, the vector front() is a built-in function used to retrieve the first element of the vector. It provides a reference to the first element, allowing you to read or modify it directly. Let’s take a quick look at a simple example that uses the vector front() method: [GFGTABS] C++ #include <bi
2 min read
Vector push_back() in C++ STL
In C++, the vector push_back() is a built-in method used to add a new element at the end of the vector. It automatically resizes the vector if there is not enough space to accommodate the new element. Let’s take a look at an example that illustrates the vector push_back() method: [GFGTABS] C++ #incl
2 min read
Vector insert() in C++ STL
In C++, the vector insert() is a built-in function used to insert new elements at the given position in a vector. In this article, we will learn about the vector insert() function in C++. Let’s take a look at an example that shows the how to use this function: [GFGTABS] C++ #include <bits/stdc++.
4 min read
vector emplace() in C++ STL
In C++, vector emplace() is used to insert elements at the given position in a vector by constructing it in-place within the vector, rather than creating a temporary object and then moving or copying it into the vector. Let's take a quick look at a simple example that uses vector emplace() method: [
4 min read
Vector assign() in C++ STL
In C++, the vector assign() is a built-in method used to assign the new values to the given vector by replacing old ones. It also modifies the size of the vector according to the given number of elements. Let’s take a look at an example that shows the how to use this function. [GFGTABS] C++ #include
4 min read
Vector erase() in C++ STL
In C++, vector erase() is a built-in function used to remove one or more elements from a vector present at a specific position or within a specified range of range. In this article, we will learn about vector erase() method in C++. Let’s take a quick look at a simple example that uses the vector era
4 min read
Other Member Methods
Vector max_size() in C++ STL
In C++, vector max_size() is a built-in function used to find the maximum number of elements that can be held by the vector container. In this article, we will learn about the vector max_size() function in C++. Let's take a look at an example that illustrates this method: [GFGTABS] CPP #include <
3 min read
Vector capacity() in C++ STL
In C++, the vector capacity() is a built-in method used to find the capacity of vector. The capacity indicates how many elements the vector can hold before it needs to reallocate additional memory. In this article, we will learn about vector capacity() method in C++. Let’s take a look at an example
3 min read
vector rbegin() and rend() Functions in C++ STL
In C++, std::vector::rbegin() and std::vector::rend() are built-in functions used to retrieve reverse iterators to the reverse beginning and reverse end of a vector. These functions allow easy traversal of vectors in reverse i.e. from the last element to the first. They are the member functions of t
3 min read
vector :: cbegin() and vector :: cend() in C++ STL
Vectors are known as dynamic arrays which can change its size automatically when an element is inserted or deleted. This storage is maintained by container. vector::cbegin() The function returns an iterator which is used to iterate container. The iterator points to the beginning of the vector.Iterat
2 min read
Vector crend() in C++ STL
In C++, the vector crend() is a built-in method used to obtain a constant reverse iterator pointing to the theoretical element just before the first element of the vector. It is used to mark the reverse end of the vector. Let’s take a look at an example: [GFGTABS] C++ #include <bits/stdc++.h>
2 min read
Vector resize() in C++ STL
In C++, the vector resize() is a built-in method used to change the size of vector container after it is declared. It can be used to increase or decrease the size of vector. Let’s take a look at an example that illustrates the vector resize() method: [GFGTABS] C++ #include <bits/stdc++.h> usin
2 min read
Vector shrink_to_fit() in C++ STL
In C++, vector shrink_to_fit() is a built-in function used to reduce the capacity of the vector to fit its size and destroys all elements beyond the size. In this article we will learn about vector shrink_to_fit() in C++. Let’s take a quick look at an example that illustrates vector shrink_to_fit()
2 min read
When to use Vector reserve() in C++?
In a vector, when the number of elements to be inserted are greater than the current capacity, it is reallocated to a larger memory block and all the items are copied to this new block making this reallocation an expensive operation with time complexity of O(n). This mechanism works well if you don'
2 min read
Vector data() in C++ STL
In C++, the vector data() is a built-in function used to access the internal array used by the vector to store its elements. In this article, we will learn about vector data() in C++. Let’s take a look at an example that illustrates the vector data() method: [GFGTABS] C++ #include <bits/stdc++.h
2 min read
2D Vector in C++
A 2D vector is a vector of the vector i.e. each element is a vector in itself. It can be visualised as a matrix where each inner vector represents a row, and the number of rows represents the maximum columns. A 2D vector is dynamically resizable in both dimensions. Let’s take a look at a simple illu
6 min read
Passing Vector to a Function in C++
To perform operations on vector belonging to one function inside other function, we pass this vector to the function as arguments during the function call. C++ provides three methods to pass a vector to a function in C++. Let's look at each of them one by one. Table of Content Pass Vector by ValuePa
5 min read
How Does a Vector Internally Works in C++?
In C++, a vector is a dynamic array that can resize itself when more elements are added or deleted. So, one may ask that how a vector internally works to achieve its dynamic resizing capability while maintaining similar efficiency to static arrays in operations? For vector to work as a resizable dyn
5 min read
How to implement our own Vector Class in C++?
The given task is to implement a class in C++ which behaves just like the Vector class.Vectors are the same as dynamic arrays with the ability to resize themselves automatically when an element is inserted or deleted, with their storage being handled automatically by the container. Vector elements a
5 min read
Advantages of Vector Over Array in C++
In C++, both vectors and arrays are used to store collections of elements, but vector offers significant advantages over arrays in terms of flexibility, functionality, and ease of use. This article explores the benefits of using vectors in C++ programming. The major advantages of vector over arrays
3 min read