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:
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
{
std::vector<> vec{, , };
std:: index = ;
(index < vec.()) {
vec.(vec.() + index);
}
( value : vec) {
std::cout << value << ;
}
}
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:
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.
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
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()
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()
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:
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.