remove remove_if

来源:互联网 发布:鄂州锦天软件 编辑:程序博客网 时间:2024/05/21 10:36

http://en.cppreference.com/w/cpp/algorithm/remove

Possible implementation

First version
template< class ForwardIt, class T >ForwardIt remove(ForwardIt first, ForwardIt last, const T& value){    first = std::find(first, last, value);    if (first != last)        for(ForwardIt i = first; ++i != last; )            if (!(*i == value))                *first++ = std::move(*i);    return first;}
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.

#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:

TextwithsomespacesTextwithsomewhitespaces


http://www.cplusplus.com/reference/algorithm/remove_if/

1234567891011121314
template <class ForwardIterator, class UnaryPredicate>  ForwardIterator remove_if (ForwardIterator first, ForwardIterator last,                             UnaryPredicate pred){  ForwardIterator result = first;  while (first!=last) {    if (!pred(*first)) {      *result = std::move(*first);      ++result;    }    ++first;  }  return result;}

12345678910111213141516171819202122
// remove_if example#include <iostream>     // std::cout#include <algorithm>    // std::remove_ifbool IsOdd (int i) { return ((i%2)==1); }int main () {  int myints[] = {1,2,3,4,5,6,7,8,9};            // 1 2 3 4 5 6 7 8 9  // bounds of range:  int* pbegin = myints;                          // ^  int* pend = myints+sizeof(myints)/sizeof(int); // ^                 ^  pend = std::remove_if (pbegin, pend, IsOdd);   // 2 4 6 8 ? ? ? ? ?                                                 // ^       ^  std::cout << "the range contains:";  for (int* p=pbegin; p!=pend; ++p)    std::cout << ' ' << *p;  std::cout << '\n';  return 0;}

0 0
原创粉丝点击