http://en.cppreference.com/w/cpp/algorithm/remove
Possible implementation
First version |
---|
Second version |
template<class ForwardIt, class UnaryPredicate> ForwardIt remove_if(ForwardIt first, ForwardIt last, UnaryPredicate p) { first = std::find_if(first, last, p); if (first != last) for(ForwardIt i = first; ++i != last; ) if (!p(*i)) *first++ = std::move(*i); return first; } |
Examples
The following code removes all spaces from a string by shifting all non-space characters to the left and then erasing the extra. This is an example of erase-remove idiom.
Run this code
#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'; std::string str2 = "Text\n with\tsome \t whitespaces\n\n"; str2.erase(std::remove_if(str2.begin(), str2.end(), [](char x){return std::isspace(x);}), str2.end()); std::cout << str2 << '\n'; }
Output:
Textwithsomespaces Textwithsomewhitespaces
http://www.cplusplus.com/reference/algorithm/remove_if/
| |
| |