In this C++ tutorial, we will learn how to declare, initialize, access, modify, insert, remove, iterate, and manage elements in a std::vector. We will also look at commonly used vector methods and links to detailed vector operations.

C++ Vector

A C++ vector is a sequence container provided by the Standard Library. Like an array, it stores elements in order and provides index-based access. Unlike a fixed-size array, a vector can automatically grow or shrink as elements are added or removed.

The std::vector class is declared in the <vector> header. All elements in a vector have the same type.

Include the C++ Vector Library

Include the <vector> header before using std::vector.

</>
Copy
#include <vector>

How to Declare a Vector in C++

The general syntax for declaring a vector is:

</>
Copy
std::vector<data_type> vector_name;

For example, the following statement creates an empty vector that can store integers.

</>
Copy
std::vector<int> numbers;

If your program contains using namespace std;, the declaration can also be written as vector<int> numbers;. Using the explicit std:: qualification makes it clear that vector belongs to the C++ Standard Library.

C++ Vector Initialization

Vectors can be initialized in several ways. The choice depends on whether you need an empty vector, a specific number of elements, repeated values, or an initial list of values.

</>
Copy
std::vector<int> a;                 // empty vector
std::vector<int> b(5);              // 5 integers, value-initialized
std::vector<int> c(5, 10);          // 5 integers, each equal to 10
std::vector<int> d{10, 20, 30, 40}; // initializer list
std::vector<int> e = d;             // copy of another vector

For std::vector<int> b(5), the five integer elements are initialized to 0.

Basic C++ Vector Example

The following example creates a vector, appends values with push_back(), accesses an element, and iterates through all elements.

</>
Copy
#include <iostream>
#include <vector>

int main() {
    std::vector<int> numbers{10, 20, 30};

    numbers.push_back(40);

    std::cout << "Second element: " << numbers[1] << '\n';

    for (int value : numbers) {
        std::cout << value << " ";
    }

    return 0;
}

Output:

Second element: 20
10 20 30 40 

Common C++ Vector Methods

The following methods cover many everyday vector operations.

Vector methodPurpose
push_back(value)Adds an element to the end.
pop_back()Removes the last element.
insert(position, value)Inserts an element before a specified iterator position.
erase(position)Removes an element at an iterator position.
clear()Removes all elements.
size()Returns the current number of elements.
empty()Checks whether the vector contains no elements.
resize(n)Changes the number of elements.
at(index)Accesses an element with bounds checking.
front()Returns a reference to the first element.
back()Returns a reference to the last element.
begin()Returns an iterator to the first element.
end()Returns an iterator just past the last element.
capacity()Returns the number of elements that can be stored before another allocation is required.
reserve(n)Requests capacity for at least n elements.
swap(other)Exchanges the contents of two vectors.

Accessing C++ Vector Elements

Vector elements can be accessed with the subscript operator [], the at() method, or the front() and back() methods.

</>
Copy
std::vector<int> values{10, 20, 30, 40};

std::cout << values[0] << '\n';   // 10
std::cout << values.at(1) << '\n'; // 20
std::cout << values.front() << '\n'; // 10
std::cout << values.back() << '\n';  // 40

operator[] does not perform bounds checking. at() checks the requested position and throws std::out_of_range if the index is invalid.

Insert an Element into a C++ Vector

Use insert() when an element has to be placed at a position other than the end. The position is specified using an iterator.

</>
Copy
std::vector<int> numbers{10, 30, 40};

numbers.insert(numbers.begin() + 1, 20);

// numbers is now {10, 20, 30, 40}

Appending with push_back() is normally the direct operation when the new element belongs at the end. Inserting near the beginning or middle can require later elements to be moved.

Vector Size and Capacity in C++

A vector’s size() and capacity() describe different things:

  • size() is the number of elements currently stored in the vector.
  • capacity() is the number of elements for which storage is currently available before the vector needs another allocation.

For example:

</>
Copy
std::vector<int> numbers;
numbers.reserve(100);

std::cout << numbers.size() << '\n';
std::cout << numbers.capacity() << '\n';

reserve(100) requests enough capacity for at least 100 elements, but it does not add 100 elements. Therefore, size() remains 0 until elements are actually inserted.

Iterating Through a C++ Vector

A vector can be traversed by index, with iterators, or with a range-based for loop. A range-based loop is convenient when every element needs to be processed in order.

</>
Copy
std::vector<int> numbers{10, 20, 30};

for (const int value : numbers) {
    std::cout << value << " ";
}

If the elements themselves need to be modified, iterate by reference.

</>
Copy
for (int& value : numbers) {
    value *= 2;
}

C++ Vector of Vectors

A vector can contain other vectors. This is commonly used for grid-like or matrix-like data where each element of the outer vector is another vector.

</>
Copy
std::vector<std::vector<int>> matrix{
    {1, 2, 3},
    {4, 5, 6}
};

std::cout << matrix[1][2]; // 6

When C++ Vector References and Iterators Can Become Invalid

Operations that change a vector can invalidate iterators, pointers, or references to its elements. In particular, an insertion that causes the vector to reallocate its storage invalidates iterators, pointers, and references to its elements. Erasing elements can also invalidate positions at and after the erased location.

If you save an iterator or reference and then modify the vector, verify that the operation does not invalidate it before using it again.


C++ Vector Operations

Vectors support operations for creating containers, accessing elements, checking their state, inserting and removing values, resizing and rearranging elements, and converting data between vectors and other types. The tutorials below cover these operations individually.


Creating and Initializing C++ Vectors

The following tutorials cover common ways to create and initialize a C++ vector, including empty vectors, vectors of a specified size, vectors with initial values, copies, and nested vectors.

  1. C++ Create an empty vector
  2. C++ Create vector of specific size
  3. C++ Create vector with initial values
  4. C++ Copy a vector to another
  5. C++ Vector length or size
  6. C++ Vector of vectors

Accessing and Iterating C++ Vector Elements

The following tutorials show how to print vector elements, traverse them with different loop forms, and access an element at a specific position.

  1. C++ Vector – Print elements
  2. C++ Vector – Iterate using For loop
  3. C++ Vector – Iterate using While loop
  4. C++ Vector – Foreach
  5. C++ Vector – Get reference to element at specific index

Checking C++ Vector Contents and State

The following tutorials cover checks such as whether a vector is empty, whether two vectors are equal, and whether a particular value is present.

  1. C++ Check if vector is empty
  2. C++ Check if two vectors are equal
  3. C++ Check if element is present in vector

Adding, Inserting, Removing, and Rearranging C++ Vector Elements

The following tutorials cover element-level changes to a vector, including appending, inserting, erasing, clearing, resizing, swapping, reversing, and sorting.

  1. C++ Add element(s) to vector
  2. C++ Append element to the end of vector
  3. C++ Append vector to another vector
  4. C++ Insert element at the beginning of vector
  5. C++ Remove first element from vector
  6. C++ Remove last element from vector
  7. C++ Remove element(s) at specific index(es) from vector
  8. C++ Remove duplicates from a vector
  9. C++ Remove elements from a vector based on a condition
  10. C++ Resize vector
  11. C++ Swap elements of two vectors
  12. C++ Remove all elements from vector
  13. C++ Reverse a vector
  14. C++ Sort a vector

Converting C++ Vectors and Other Data Types

The following tutorials cover conversions from vectors to other types and from other data structures to vectors.

  1. C++ Convert array to vector
  2. C++ Convert vector to map
  3. C++ Join elements of vector to a string

C++ Vector Programs for Filtering, Sorting, and Splitting

These examples apply vector operations to common programming tasks such as filtering values, finding unique elements, sorting, and splitting a vector.

  1. C++ Filter even numbers in an integer vector
  2. C++ Filter odd numbers in an integer vector
  3. C++ Get unique elements of a vector
  4. C++ Remove empty string elements from a string vector
  5. C++ Sort integer vector in ascending order
  6. C++ Sort integer vector in descending order
  7. C++ Sort string vector based on length
  8. C++ Sort string vector lexicographically
  9. C++ Split vector into two equal halves

Key Points About C++ Vectors

  • Use #include <vector> to make std::vector available.
  • A vector stores elements of one declared type in sequence and supports random-access indexing.
  • Use push_back() to append an element and pop_back() to remove the final element.
  • Use insert() and erase() for changes at iterator positions.
  • Use size() for the number of stored elements and capacity() for currently allocated element capacity.
  • Use at() when bounds-checked access is required.
  • Be careful with saved iterators, references, and pointers after operations that insert, erase, or otherwise reallocate vector storage.