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.
#include <vector>
How to Declare a Vector in C++
The general syntax for declaring a vector is:
std::vector<data_type> vector_name;
For example, the following statement creates an empty vector that can store integers.
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.
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.
#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 method | Purpose |
|---|---|
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.
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.
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:
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.
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.
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.
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.
- C++ Create an empty vector
- C++ Create vector of specific size
- C++ Create vector with initial values
- C++ Copy a vector to another
- C++ Vector length or size
- 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.
- C++ Vector – Print elements
- C++ Vector – Iterate using For loop
- C++ Vector – Iterate using While loop
- C++ Vector – Foreach
- 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.
- C++ Check if vector is empty
- C++ Check if two vectors are equal
- 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.
- C++ Add element(s) to vector
- C++ Append element to the end of vector
- C++ Append vector to another vector
- C++ Insert element at the beginning of vector
- C++ Remove first element from vector
- C++ Remove last element from vector
- C++ Remove element(s) at specific index(es) from vector
- C++ Remove duplicates from a vector
- C++ Remove elements from a vector based on a condition
- C++ Resize vector
- C++ Swap elements of two vectors
- C++ Remove all elements from vector
- C++ Reverse a vector
- 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.
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.
- C++ Filter even numbers in an integer vector
- C++ Filter odd numbers in an integer vector
- C++ Get unique elements of a vector
- C++ Remove empty string elements from a string vector
- C++ Sort integer vector in ascending order
- C++ Sort integer vector in descending order
- C++ Sort string vector based on length
- C++ Sort string vector lexicographically
- C++ Split vector into two equal halves
Key Points About C++ Vectors
- Use
#include <vector>to makestd::vectoravailable. - A vector stores elements of one declared type in sequence and supports random-access indexing.
- Use
push_back()to append an element andpop_back()to remove the final element. - Use
insert()anderase()for changes at iterator positions. - Use
size()for the number of stored elements andcapacity()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.
TutorialKart.com