Home > Article > Backend Development > How to Efficiently Remove Elements by Value from an STL Vector?
Efficient Value Removal from STL Vector
Despite the extensive functionalities provided by the STL vector class, it lacks an explicit function to expunge elements based on their values. This operation, however, is commonly encountered.
Solution: Employing std::remove
STL offers the std::remove function, which doesn't explicitly remove elements but relocates elements to be retained to the beginning of the container. It returns an iterator pointing past these retained elements:
auto new_end = std::remove(vec.begin(), vec.end(), int_to_remove);
To complete the removal, we can use vec.erase to eliminate the excess elements now located at the end:
vec.erase(new_end, vec.end());
This approach effectively purges elements with the target value while preserving the vector's contiguous structure.
The above is the detailed content of How to Efficiently Remove Elements by Value from an STL Vector?. For more information, please follow other related articles on the PHP Chinese website!