C++ std::vector::erase() and std::remove() Explained
The std::remove() and std::erase() algorithms in C++ are powerful tools for manipulating elements within a std::vector. Let's explore how they work together to efficiently remove elements that meet a specific condition.
Understanding the Process
-
std::remove(): This algorithm doesn't actually remove elements from the vector. Instead, it rearranges the elements so that all elements satisfying the given condition are moved to the end of the vector. The function returns an iterator pointing to the new logical end of the vector. -
std::erase(): This algorithm removes a range of elements from the vector, starting from a specified iterator and ending at the vector's end.
Example: Removing Even Numbers from a Vector
#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 num) { return num % 2 == 0; }), numbers.end());
// Print the remaining numbers
for (int num : numbers) {
std::cout << num << ' ';
}
std::cout << std::endl;
return 0;
}
Explanation:
-
std::remove_if()iterates through the vector, applying the lambda function[](int num) { return num % 2 == 0; }to each element. This lambda checks if the number is even and returns true if it is. -
The
std::remove_if()function rearranges the vector, placing all even numbers at the end. It then returns an iterator pointing to the new logical end of the vector (where the even numbers are now). -
std::erase()takes the iterator returned bystd::remove_if()and the original end iterator as arguments. It then removes the elements from the new logical end to the original end (the even numbers).
Key Points:
std::remove()does not modify the vector's size, it merely rearranges elements.std::erase()is used afterstd::remove()to remove the unwanted elements from the vector.- Use
std::remove_if()to remove elements based on a condition, using a lambda expression for greater flexibility.
Remember: This approach is more efficient than iterating through the vector and manually removing elements, especially for large vectors. This is because std::remove() and std::erase() provide optimized algorithms for these operations.
原文地址: https://www.cveoy.top/t/topic/olJk 著作权归作者所有。请勿转载和采集!