How to Use remove in C++: Syntax, Example, and Tips
std::remove is used to move all elements equal to a given value to the end of a container and returns an iterator to the new logical end. It does not actually erase elements; to remove them from containers like std::vector, you combine std::remove with the container's erase method.Syntax
The std::remove function is declared in the <algorithm> header and has this form:
std::remove(begin, end, value)
Where:
beginandendare iterators defining the range to process.valueis the element to remove.
The function returns an iterator pointing to the new end of the range after "removal".
Note: std::remove only reorders elements; it does not change the container size.
#include <algorithm> #include <vector> #include <iostream> // Syntax example std::vector<int> v = {1, 2, 3, 2, 4}; auto new_end = std::remove(v.begin(), v.end(), 2);
Example
This example shows how to remove all occurrences of the number 2 from a std::vector. It uses std::remove to move unwanted elements to the end, then erases them to actually shrink the vector.
#include <iostream> #include <vector> #include <algorithm> int main() { std::vector<int> numbers = {1, 2, 3, 2, 4, 2, 5}; // Remove all 2's auto new_end = std::remove(numbers.begin(), numbers.end(), 2); // Erase the "removed" elements numbers.erase(new_end, numbers.end()); // Print the result for (int n : numbers) { std::cout << n << ' '; } std::cout << '\n'; return 0; }
Common Pitfalls
1. Forgetting to erase after remove: std::remove only moves elements but does not reduce container size, so the container still holds "removed" elements at the end.
2. Using remove on containers without erase: For containers like std::list, use remove member function instead.
3. Misunderstanding return value: The returned iterator marks the new logical end; elements beyond it are unspecified.
#include <vector> #include <algorithm> #include <iostream> int main() { std::vector<int> v = {1, 2, 3, 2, 4}; // Wrong: only remove, no erase std::remove(v.begin(), v.end(), 2); // Vector size remains 5 std::cout << "Size after remove without erase: " << v.size() << '\n'; // Correct: remove + erase auto new_end = std::remove(v.begin(), v.end(), 2); v.erase(new_end, v.end()); std::cout << "Size after remove and erase: " << v.size() << '\n'; return 0; }
Quick Reference
Tips for using std::remove:
- Always include
<algorithm>header. - Use with containers supporting forward iterators like
std::vectororstd::deque. - Combine with container's
eraseto actually remove elements. - For
std::list, use its memberremovemethod instead.