Question
I have a std::vector<int> and want to remove the element at a specific position, such as the nth element. How can I do that in C++?
Example:
#include <vector>
std::vector<int> vec;
vec.push_back(6);
vec.push_back(-17);
vec.push_back(12);
// How do I remove the element at index n?
vec.erase(???);
Short Answer
By the end of this page, you will understand how std::vector::erase() works in C++, why it takes an iterator instead of a raw index, how to remove a single element by index safely, and what happens to the remaining elements after removal.
Concept
std::vector stores elements in a contiguous block of memory, like an array that can grow dynamically. When you remove an element from the middle, all later elements must shift left by one position to fill the gap.
In C++, removing elements from a vector is usually done with the erase() member function. The important detail is that erase() does not take an index directly. It takes an iterator pointing to the element to remove.
That is why removing by index looks like this:
vec.erase(vec.begin() + index);
Here is what each part means:
vec.begin()returns an iterator to the first element+ indexmoves that iterator forward byindexpositionserase(...)removes the element at that iterator
This matters because much of the C++ Standard Library uses iterators as the general way to refer to positions inside containers.
A key behavior to remember:
- The erased element is removed
- All elements after it shift left
- The vector size decreases by 1
- Iterators and references at or after the erased position may become invalid
So, if you remove index 1 from this vector:
{6, -17, 12}
you get:
{6, 12}
Mental Model
Think of a std::vector like a row of numbered boxes on a shelf.
If you remove the box in the middle, the boxes to the right slide left so there is no empty gap.
So if the shelf contains:
Index: 0 1 2
Value: 6 -17 12
and you remove index 1, the value 12 slides into its place:
Index: 0 1
Value: 6 12
erase() needs an iterator because, in C++, containers are usually manipulated by positions represented as iterators rather than plain numeric indexes.
Syntax and Examples
Basic syntax
vec.erase(vec.begin() + index);
This removes one element at index.
Example
#include <iostream>
#include <vector>
int main() {
std::vector<int> vec{6, -17, 12};
std::size_t index = 1;
vec.erase(vec.begin() + index);
for (int value : vec) {
std::cout << value << ' ';
}
}
Output:
6 12
Safer version with bounds checking
You should make sure the index is valid before erasing:
#include <iostream>
#include <vector>
int main() {
std::vector<int> vec{6, -17, 12};
std::size_t index = 1;
if (index < vec.size()) {
vec.erase(vec.begin() + index);
}
for (int value : vec) {
std::cout << value << ' ';
}
}
Removing the last element
If you want to remove the last element, you can do either of these:
vec.erase(vec.end() - 1);
or more simply:
vec.pop_back();
Use pop_back() when you specifically want to remove the last element, because it is clearer.
Step by Step Execution
Consider this code:
#include <vector>
std::vector<int> vec{6, -17, 12};
std::size_t index = 1;
vec.erase(vec.begin() + index);
Step by step:
-
vecstarts as:[6, -17, 12] -
indexis1 -
vec.begin()points to the first element,6 -
vec.begin() + indexmoves one position forward, so it points to-17 -
vec.erase(...)removes the element at that position -
The remaining elements shift left
-
vecbecomes:[6, 12] -
vec.size()changes from3to2
Another trace
std::vector<int> numbers{10, 20, 30, 40};
numbers.erase(numbers.begin() + 2);
Before:
Index: 0 1 2 3
Value: 10 20 30 40
After removing index 2:
Index: 0 1 2
Value: 10 20 40
Real World Use Cases
Removing an element by index is common in many types of programs.
User interfaces
- Remove a selected item from a list
- Delete a row from a table model
- Remove a recent search entry
Game development
- Remove a defeated enemy from an active list
- Delete an item from a player's inventory slot
- Remove an expired effect from a sequence of status effects
Data processing
- Drop a bad record at a known position
- Remove a column index from a list of selected fields
- Delete a temporary result from a working collection
APIs and backend systems
- Remove a task from an in-memory queue by position
- Delete a failed batch item before retrying others
- Remove a step from a configurable workflow
Whenever order matters and you need random access, std::vector is often used, and erase() is the tool for removal.
Real Codebase Usage
In real projects, developers rarely write erase(begin() + index) without some validation around it.
Common pattern: guard clause
void removeAt(std::vector<int>& vec, std::size_t index) {
if (index >= vec.size()) {
return;
}
vec.erase(vec.begin() + index);
}
This avoids invalid access.
Returning success or failure
bool removeAt(std::vector<int>& vec, std::size_t index) {
if (index >= vec.size()) {
return false;
}
vec.erase(vec.begin() + index);
return true;
}
This is useful in business logic or APIs.
Erasing while iterating
When removing elements based on a condition, developers often use iterators carefully or use algorithms such as remove_if plus erase.
#include <algorithm>
#include <vector>
std::vector<int> vec{1, 2, 3, 4, 5};
vec.erase(std::remove_if(vec.begin(), vec.end(), [](int x) {
return x % 2 == 0;
}), vec.end());
This is not removal by index, but it is a very common real-world pattern related to erase().
Important design note
If your code frequently inserts and removes elements in the middle, std::vector may not always be the best container. But it is still often chosen because of its cache-friendly layout and fast random access.
Common Mistakes
1. Passing an index directly to erase()
Broken code:
vec.erase(1);
Why it is wrong:
erase()expects an iterator, not an integer index
Correct version:
vec.erase(vec.begin() + 1);
2. Not checking bounds
Broken code:
std::size_t index = 10;
vec.erase(vec.begin() + index);
Why it is wrong:
- If
index >= vec.size(), the iterator is invalid - This causes undefined behavior
Correct version:
if (index < vec.size()) {
vec.erase(vec.begin() + index);
}
3. Using end() as if it points to the last element
Broken code:
vec.erase(vec.end());
Why it is wrong:
vec.end()points past the last element- It is not a valid element to erase by itself
Correct version:
vec.erase(vec.end() - 1);
Or better for the last element:
vec.pop_back();
4. Forgetting that indexes change after erase
std::vector<int> vec{10, 20, 30, 40};
vec.erase(vec.begin() + 1);
After this:
20is removed30moves to index140moves to index2
Do not keep using old positions as if nothing changed.
5. Reusing invalid iterators or references
Broken idea:
auto it = vec.begin() + 1;
vec.erase(it);
// using it again here is unsafe
After erase(), iterators and references at or after the erased position may be invalid.
Use the iterator returned by erase() if needed:
auto it = vec.erase(vec.begin() + 1);
This returned iterator points to the next valid element, or end() if none remains.
Comparisons
| Task | Best choice | Notes |
|---|---|---|
| Remove element at a known index | vec.erase(vec.begin() + index) | General solution for index-based removal |
| Remove last element | vec.pop_back() | Simpler and clearer than erase(end() - 1) |
| Remove a range of elements | vec.erase(first, last) | Removes multiple consecutive elements |
| Remove by value or condition | remove/remove_if + erase | Standard erase-remove idiom |
erase() vs pop_back()
| Feature | erase() | pop_back() |
|---|---|---|
| Removes from middle | Yes | No |
| Removes last element | Yes | Yes |
| Takes iterator | Yes | No |
| Simpler for last item | No | Yes |
std::vector vs std::list for removals
| Container | Middle removal | Random access | Memory layout |
|---|---|---|---|
std::vector | Slower because elements shift | Fast | Contiguous |
std::list | Fast at known iterator position | Slow | Non-contiguous |
Even though middle removal is more expensive in std::vector, it is still commonly used because indexing and iteration are very efficient.
Cheat Sheet
Remove one element by index
vec.erase(vec.begin() + index);
Safe version
if (index < vec.size()) {
vec.erase(vec.begin() + index);
}
Remove last element
vec.pop_back();
or
vec.erase(vec.end() - 1);
Remove a range
vec.erase(vec.begin() + start, vec.begin() + end);
Removes elements in [start, end).
Important rules
erase()takes an iterator, not an indexbegin() + indexgives the iterator for that index- Check that
index < vec.size() end()is past the last element- Elements after the erased one shift left
- Iterators and references may be invalidated after erase
Return value
erase() returns an iterator to the next element after the erased one.
auto it = vec.erase(vec.begin() + index);
Time cost
- Removing from the end: cheap with
pop_back() - Removing from the middle: later elements must move
FAQ
How do I erase the nth element from a std::vector in C++?
Use:
vec.erase(vec.begin() + n);
Make sure n < vec.size() first.
Why does std::vector::erase() take an iterator instead of an index?
The C++ Standard Library uses iterators as a general way to refer to positions in containers. This keeps the interface consistent across many container types.
Can I write vec.erase(2)?
No. That passes an integer, not an iterator. Use:
vec.erase(vec.begin() + 2);
What happens after erasing an element from a vector?
The element is removed, later elements shift left, and the vector size decreases.
Is it safe to erase while looping through a vector?
It can be, but you must handle iterators carefully because erase() may invalidate them. Often, using the iterator returned by erase() is the correct approach.
How do I remove the last element from a vector?
Use:
vec.pop_back();
This is the simplest and clearest option.
What if the index is out of range?
Then vec.begin() + index is invalid, and using it causes undefined behavior. Always check bounds first.
Mini Project
Description
Build a small C++ program that manages a list of numbers and lets you remove an item by index. This demonstrates how to convert an index into an iterator, validate user input, and update the vector safely after deletion.
Goal
Create a program that stores several integers in a std::vector, removes one item at a chosen index, and prints the updated result.
Requirements
- Create a
std::vector<int>with at least five values. - Ask the user for an index to remove.
- Check whether the index is valid before erasing.
- Remove the element using
erase(). - Print the vector before and after removal.
Keep learning
Related questions
Advantages of Brace Initialization in C++
Learn why C++ brace initialization is often clearer and safer than other object initialization styles, with examples and common pitfalls.
Basic Rules and Idioms for Operator Overloading in C++
Learn the core rules, syntax, and common idioms for operator overloading in C++, including member vs non-member operators.
C++ Aggregates, Trivial Types, Trivially Copyable Types, and PODs Explained
Learn what aggregates, trivial types, trivially copyable types, and PODs mean in C++, how they differ, and why they matter.