Erasing Elements from an STL Vector by Value
When working with STL vectors, removing an element by its value may appear to be a basic operation, yet there seems to be no straightforward method within the vector class itself.
The std::remove function provides a solution for this common task. However, it's important to note that std::remove does not directly remove elements from the container. Instead, it repositions elements that satisfy a given condition to the beginning of the container. To complete the removal process, this modified container must be passed to container_type::erase to remove the redundant elements now located at the end.
Consider the following example:
std::vector<int> vec; // .. populate vec .. int int_to_remove = n; vec.erase(std::remove(vec.begin(), vec.end(), int_to_remove), vec.end());
In this example, std::remove repositions all elements not equal to int_to_remove to the beginning of the vector, and returns an iterator pointing to the first element after these elements. This iterator is then used as the argument to std::erase(), effectively removing the remaining elements at the end of the vector.
The above is the detailed content of How Do I Efficiently Remove Elements by Value from an STL Vector?. For more information, please follow other related articles on the PHP Chinese website!