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. |
|---|