C++ <vector> erase function
eraseis used in vector todelete the element at the specified positionis the most flexible deletion method in containers.
eraseis a member function of container classes, used toDeletes one or more elements at specified positions in the container.. It accepts an iterator parameter.
eraseProvides the ability to delete elements at any position, although it is less efficient in vector thanpop_back(requiring moving subsequent elements), but it is more powerful.
Word Definitions: eraseMeans "erase", i.e., delete the element at the specified position.
Basic syntax and parameters
eraseIt is a member function of container classes, requiring an iterator that specifies the position to delete.
Syntax format
// 删除 pos 位置的元素 iterator erase(iterator pos); // 删除 [first, last) 范围内的所有元素 iterator erase(iterator first, iterator last);
Parameter description
- Parameter:
pos- Type: iterator (
iterator) - Description: The position of the element to delete.
- Type: iterator (
- Parameter:
first,last- Type: iterator (
iterator) - Description: The start and end iterators of the range of elements to delete. The deletion range is [
first,last), i.e. includesfirstdoes not includelast。
- Type: iterator (
- Return Value: Returns an iterator pointing to the position after the last deleted element (i.e., the original
lastelement at the position). - Effect: Deletes the element at the specified position, and subsequent elements move forward one by one.
- Note:
eraseAfter deleting elements, the following elements move forward, and iterators may become invalid.
Function description
Example
Let us thoroughly master it through a series of examples.eraseUsage.
Example 1: Basic usage - deleting a single element
Example
#include <vector>
int main() {
std::vector<int> numbers = {1, 2, 3, 4, 5};
std::cout << "Original vector: ";
for(int n : numbers) std::cout << n << " ";
std::cout << std::endl;
// Remove the element at the second position (index 1)
auto it = numbers.begin() + 1;
numbers.erase(it);
std::cout << "After deletion: ";
for(int n : numbers) std::cout << n << " ";
std::cout << std::endl;
return 0;
}
Expected running result:
原始 vector: 1 2 3 4 5 After deletion: 1 3 4 5
Code analysis:
numbers.begin() + 1Points to the second element (with value 2).eraseDeletes the element at that position.- Subsequent elements (3, 4, 5) all move forward by one position.
Example 2: Deleting the first and last elements
Usagebegin()andend()Can delete the first and last elements.
Example
#include <vector>
int main() {
std::vector<int> numbers = {10, 20, 30, 40, 50};
std::cout << "Original: ";
for(int n : numbers) std::cout << n << " ";
std::cout << std::endl;
// Remove the first element
numbers.erase(numbers.begin());
std::cout << "After removing the first element: ";
for(int n : numbers) std::cout << n << " ";
std::cout << std::endl;
// Remove the last element (end() points one past the last element)
numbers.erase(numbers.end() - 1);
std::cout << "After removing the last element: ";
for(int n : numbers) std::cout << n << " ";
std::cout << std::endl;
return 0;
}
Expected running result:
原始: 10 20 30 40 50 删除第一个元素后: 20 30 40 50 删除最后一个元素后: 20 30 40
Code analysis:
erase(begin())Delete the first element.erase(end() - 1)Delete the last element (noteend()points to one past the last element).
Example 3: Deleting multiple elements (range)
All elements within the specified range can be deleted.
Example
#include <vector>
int main() {
std::vector<int> numbers = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
std::cout << "Original: ";
for(int n : numbers) std::cout << n << " ";
std::cout << std::endl;
// Remove the second through fifth elements (indices 1 to 4)
auto first = numbers.begin() + 1;
auto last = numbers.begin() + 5;
numbers.erase(first, last);
std::cout << "After removing positions [1, 5): ";
for(int n : numbers) std::cout << n << " ";
std::cout << std::endl;
return 0;
}
Expected running result:
原始: 1 2 3 4 5 6 7 8 9 10 删除位置 [1, 5) 后: 1 6 7 8 9 10
Code analysis:
erase(first, last)Remove fromfirsttolastall elements before.- Here, the elements at indices 1, 2, 3, 4 (2, 3, 4, 5) are deleted.
Example 4: Deleting all odd numbers
Combined with a loop, elements that satisfy a condition can be deleted.
Example
#include <vector>
int main() {
std::vector<int> numbers = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
std::cout << "Original: ";
for(int n : numbers) std::cout << n << " ";
std::cout << std::endl;
// Remove all odd numbers
for(auto it = numbers.begin(); it != numbers.end(); ) {
if(*it % 2 == 1) { // If it is odd
it = numbers.erase(it); // erase returns the iterator to the next element
} else {
++it;
}
}
std::cout << "After removing odd numbers: ";
for(int n : numbers) std::cout << n << " ";
std::cout << std::endl;
return 0;
}
Expected running result:
原始: 1 2 3 4 5 6 7 8 9 10 删除奇数后: 2 4 6 8 10
Code analysis:
- When deleting elements in a loop, be careful to update the iterator.
eraseReturns an iterator pointing to the next element; this is the correct way to delete.
Example 5: The efficiency issue of erase
When used in a vectoreraseDeleting elements in the middle is less efficient.
Example
#include <vector>
#include <chrono>
int main() {
const int N = 10000;
// Remove the first element (inefficient)
std::vector<int> v1;
for(int i = 0; i < N; ++i) v1.push_back(i);
auto start1 = std::chrono::high_resolution_clock::now();
while(!v1.empty()) {
v1.erase(v1.begin());
}
auto end1 = std::chrono::high_resolution_clock::now();
auto duration1 = std::chrono::duration_cast<std::chrono::microseconds>(end1 - start1);
// Remove the last element (efficient)
std::vector<int> v2;
for(int i = 0; i < N; ++i) v2.push_back(i);
auto start2 = std::chrono::high_resolution_clock::now();
while(!v2.empty()) {
v2.pop_back();
}
auto end2 = std::chrono::high_resolution_clock::now();
auto duration2 = std::chrono::duration_cast<std::chrono::microseconds>(end2 - start2);
std::cout << "Removing from the beginning " << N << elements took: << duration1.count() << " microseconds" << std::endl;
std::cout << "Removing from the end " << N << elements took: << duration2.count() << " microseconds" << std::endl;
return 0;
}
Code analysis:
- Deleting an element from the beginning of a vector requires moving all subsequent elements, which is very inefficient.
- Deleting elements from the end (
pop_back) does not require moving elements and is efficient. - If you need to frequently delete elements from the beginning, consider using
dequeorlist。
Example 6: Using erase to implement data filtering
eraseCan be used to filter data.
Example
#include <vector>
#include <string>
// Simple filtering of failing grades
void filterFailing(std::vector<int>& scores) {
for(auto it = scores.begin(); it != scores.end(); ) {
if(*it < 60) {
it = scores.erase(it);
} else {
++it;
}
}
}
int main() {
std::vector<int> scores = {85, 92, 45, 78, 55, 90, 67};
std::cout << Original score:;
for(int s : scores) std::cout << s << " ";
std::cout << std::endl;
filterFailing(scores);
std::cout << Passing score:;
for(int s : scores) std::cout << s << " ";
std::cout << std::endl;
return 0;
}
Expected running result:
原始成绩: 85 92 45 78 55 90 67 及格成绩: 85 92 78 90 67
Code analysis:
- Usage
eraseCan implement conditional filtering. - Delete scores that are failing (less than 60 points).
other extensions