您的位置:首页 > 其它

remove remove_if

2015-06-08 11:30 225 查看
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.

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/
1
2
3
4
5
6
7
8
9
10
11
12
13
14

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;
}

1
2
3
4
5
6
7
8
9
10
11
12
13
1415
16
17
18
19
20
21
22

// remove_if example
#include <iostream>     // std::cout
#include <algorithm>    // std::remove_if

bool 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;
}

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: