Consider the following code (taken from cppreference.com, slightly adapted):
#include <algorithm>
#include <string>
#include <iostream>
#include <cctype>
int main()
{
std::string str1 = " Text with some spaces";
str1.erase(std::remove(str1.begin(), str1.end(), ' '), str1.end());
std::cout << str1 << '\n';
return 0;
}
Why is the second parameter to erase
neccessary? (I.e. str1.end()
in this case.)
Why can't I just supply the iterators which are returned by remove
to erase
? Why do I have to tell it also about the last element of the container from which to erase?
The pitfall here is that you can also call erase
without the second parameter but that produces the wrong result, obviously.
Are there use cases where I would not want to pass the end of the container as a second parameter to erase
?
Is omitting the second parameter of erase
for the erase-remove idiom always an error or could that be a valid thing to do?
erase
takes a begin and end iterator.remove
shuffles (kind of) the items to remove to the end, and returns a "new ending" iterator -- which is passed to theerase
function as the start of the range to erase. You could make a helper function that does these two operations for you in one function call. – Downtroddenerase
a range other than the one identified byremove
. – Lumbye