The Wayback Machine - https://web.archive.org/web/20250304001922/https://www.geeksforgeeks.org/vector-in-cpp-stl/
Open In App

Vector in C++ STL

Last Updated : 27 Feb, 2025
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Share
Report
News Follow

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:

C++
#include <iostream>
#include <vector>
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;
}

Output
1 4 2 3 5 

Explanation: In this program, we create a vector of integers v that stores the elements {1, 4, 2, 3, 5}.

Syntax of Vector

Vector is defined as the std::vector class template inside the <vector> header file.

vector<T> vec_name;

where,

  • T: Type of elements in the vector.
  • vec_name: Name assigned to the vector.

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 in the example below:

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;
}

Output
1 4 2 3 5 
9 9 9 9 9 

In the above example,

  • vector<int> v1 creates an empty vector. This is called default initialization.
  • vector<int> v2 = {1, 4, 2, 3, 5} initializes a vector with given values.
  • vector<int> v3(5, 9) creates a vector of size 5, each element initialized to 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. 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.

Example:

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;
}

Output
a c f d z 

More ways to insert an element in the vector are discussed in the article – Different Ways to Add Elements in a Vector

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

Example:

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;
}

Output
d
f

To know more about accessing vector elements, refer to the article – Different Ways to Access Elements in Vector

3. Updating Elements

Updating elements is very similar to the accessing except that we use an assignment operator to assign a new value to a particular element. It uses the same methods: [] subscript operator and vector at().

Example:

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;
}

Output
D
F

More methods to update vector elements are discussed in this article – Different Ways to Update Vector Elements

4. Traversing

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.

We can also use a range-based loop for simple traversal.

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

int main() {
    vector<char> v = {'a', 'c', 'f', 'd', 'z'};

    // Traversing vector using range based for loop
      for (auto x: v)
        cout << x << " ";
    return 0;
}

Output
a c f d z 

More ways to traverse vectors are discussed in this article – Different Ways to Iterate Through Vector

5. Finding Elements

The vector container does not provide the specialized function to find the element. Though, we can search for the element using find() algorithm.

Example:

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

int main() {
    vector<char> v = {'a', 'c', 'f', 'd', 'z'};
    
    // Find the element 'f'
    auto it = find(v.begin(), v.end(), 'f');
    
    cout << *it;
    return 0;
}

Output
f

In this example, the find() function searches for the element ‘f’ in the vector v. It returns an iterator pointing to the first occurrence of ‘f’, which is then dereferenced to print the character.

More ways to search elements in a vector are discussed in this article – Different Ways to Find an Element in Vector

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

Example:

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;
}

Output
a c f d 
a c d 

To know more about the deletion of an element in the vector, refer to this article – Different Ways to Remove Elements from Vector

Time Complexity

The below table lists the time complexity of the above operations on a vector:

OperationTime Complexity
Insert an element at the endO(1) (amortized)
Insert an element somewhere in the middleO(n)
Delete an element from the endO(1)
Delete an element from somewhere in the middleO(n)
Access an element by indexO(1)
Traverse the vectorO(n)

Find an element by value

O(n)

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.

Learn C++ Online – Master everything from basics to advanced concepts. Apply your knowledge with practical exercises and boost your skills. Take the Three 90 Challenge: finish 90% in 90 days for a 90% refund. Start now and level up your C++ programming!


Practice Tags :

Similar Reads

Initializing Vector using an Existing Vector in C++ STL
A vector is a type of container which can store objects of similar data type. Vector acts like a dynamic array where we can insert elements and the size of the array increases depending upon the elements inserted. Syntax: vector<data_structure/type> vector_name(size, item) To know more about vectors refer to vectors in C++. The 3D vector in C
5 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.Iterator cannot modify the contents of the vector. Synta
2 min read
How to Append a Vector to a Vector in C++?
Appending a vector to another vector means adding all the elements of one vector at the last of other vector. In this article, we will learn how to append a vector to another vector in C++.ExamplesInput: v1= {10, 20, 30}, v2= {70, 80, 90};Output: 10 20 30 70 80 90Explanation: Elements of v2 are added at the end of v1Input: v1 = {12, 45, 21, 78}, v2
4 min read
How to Access Vector Methods from Pointer to Vector in C++?
In C++, we can create a pointer that points to the object of vector type. In this article, we will learn how to access member functions of std::vector from a pointer to the vector in C++. Example Input:vec = {1, 2, 3, 4}vector<int>* ptr = vecOutput:ptr->at(2): 3Accessing std::vector Methods using Pointers in C++We can access the member fun
2 min read
How to flatten a Vector of Vectors or 2D Vector in C++
Given a Vector of Vectors (2D vector), the task is to flatten this 2d vector. Examples: Input: vector = [[1, 2, 3, 4], [5, 6], [7, 8]] Output: 1 2 3 4 5 6 7 8 Input: vector = [[1, 2], [3], [4, 5, 6, 8]] Output: 1 2 3 4 5 6 8 Algorithm: 2D Vector can be flattened using iterators.Store starting and ending iterator of every vector in two arrays, iStar
2 min read
Is std::vector or boost::vector Thread Safe?
In C++, a common question that arises is: Is std::vector or boost::vector thread-safe? The straightforward answer is no, neither std::vector nor boost::vector is thread-safe.In this article, we will learn why std::vector and boost::vector are not thread-safe and explore some practical alternatives for making them safe to use in a multi-threaded env
5 min read
When should I use Vector at() instead of vector operator[]?
In C++, vector provides two methods for accessing its elements using indexes: vector operator[] and vector at(). Although both methods provide similar functionality, but there are some differences between them.The following table lists the primary differences between the vector operator[] and vector at():Parametervector operator[]vector at()Bound C
2 min read
Vector resize() vs Vector reserve()
In C++, vector resize() and vector reserve() are two member methods of vector to manage memory of the container. In this article, we will learn the differences between vector resize() and vector reserve() method in C++.Vector size() modifies the size of the vector, i.e., the number of elements currently present in the vector.Vector reserve() is use
3 min read
Find and print duplicate words in std::vector<string> using STL functions
Consider an array of string and find duplicate words in that array and print that duplicate words if exist.Examples: Input : { "welcome", "to", "geeks", "for", "geeks" } Output : geeks Input : { "reduce", "reuse", "recycle", "reduce", "reuse", "recycle", " recycle" } Output : recycle reduce reuse Input : { "Go", "Green" } Output : No Duplicate wo
2 min read
Create a balanced BST using vector in C++ STL
Given an unsorted vector arr, the task is to create a balanced binary search tree using the elements of the array. Note: There can be more than one balanced BST. Forming any is acceptable Examples: Input: arr[] = { 2, 1, 3}Output: 2 1 3Explanation: The tree formed is show below. The preorder traversal is 2 1 3 2 / \ 1 3 Input: arr[] =
5 min read