Removing objects from a std::vector
is a common operation, and C++ provides several ways to do this depending on your specific needs. Let's explore the main approaches.
erase()
The erase()
function is the most straightforward way to remove elements from a std::vector
. It can remove a single element or a range of elements:
#include <iostream>
#include <vector>
int main(){
std::vector<int> numbers{1, 2, 3, 4, 5};
// Remove the third element (index 2)
numbers.erase(numbers.begin() + 2);
// Print the vector
for (int num : numbers) {
std::cout << num << ' ';
}
std::cout << '\n';
// Remove a range (first two elements)
numbers.erase(
numbers.begin(),
numbers.begin() + 2);
// Print the vector again
for (int num : numbers) {
std::cout << num << ' ';
}
}
1 2 4 5
4 5
remove()
and erase()
For more complex removal conditions, you can use the remove()
algorithm along with erase()
. This is known as the erase-remove idiom:
#include <iostream>
#include <vector>
#include <algorithm>
int main(){
std::vector<int> numbers{
1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
// Remove all even numbers
numbers.erase(
std::remove_if(
numbers.begin(), numbers.end(),
[](int n){ return n % 2 == 0; }),
numbers.end());
// Print the vector
for (int num : numbers) {
std::cout << num << ' ';
}
}
1 3 5 7 9
pop_back()
If you only need to remove the last element, use pop_back()
:
#include <iostream>
#include <vector>
int main(){
std::vector<int> numbers{1, 2, 3, 4, 5};
numbers.pop_back();
// Print the vector
for (int num : numbers) {
std::cout << num << ' ';
}
}
1 2 3 4
Remember that removing elements from the middle of a std::vector
can be expensive, as it requires shifting all subsequent elements. If you frequently need to remove elements from arbitrary positions, consider using std::list
 instead.
Also, be cautious when removing elements while iterating over a vector. Removing an element invalidates iterators at or after the point of removal. Here's a safe way to remove elements while iterating:
#include <iostream>
#include <vector>
int main(){
std::vector<int> numbers{
1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
for (auto it = numbers.begin();
it != numbers.end();) {
if (*it % 2 == 0) {
it = numbers.erase(it);
} else { ++it; }
}
// Print the vector
for (int num : numbers) {
std::cout << num << ' ';
}
}
1 3 5 7 9
By using these techniques, you can effectively remove objects from a std::vector
in various scenarios, whether you're removing single elements, ranges, or elements that meet specific criteria.
Answers to questions are automatically generated and may not have been reviewed.
std::vector
Explore the fundamentals of dynamic arrays with an introduction to std::vector