std::remove, std::remove_if
来自cppreference.com
该页由英文版wiki使用Google Translate机器翻译而来。
该翻译可能存在错误或用词不当。鼠标停留在文本上可以看到原版本。你可以帮助我们修正错误或改进翻译。参见说明请点击这里. |
在头文件 <algorithm> 中定义
|
||
template< class ForwardIt, class T > ForwardIt remove( ForwardIt first, ForwardIt last, const T& value ); |
(1) | |
template< class ForwardIt, class UnaryPredicate > ForwardIt remove_if( ForwardIt first, ForwardIt last, UnaryPredicate p ); |
(2) | |
满足特定条件的范围内
[first, last)
中移除所有元素。第一个版本中删除所有元素,等于value
,第二个版本中删除所有元素的谓词p
回报true. 原文:
Removes all elements satisfying specific criteria from the range
[first, last)
. The first version removes all elements that are equal to value
, the second version removes all elements for which predicate p
returns true. 卸下做是通过移动的元素的范围内以这样的方式,要被擦除的元素将被覆盖。元素之间的旧的和新的范围的两端有未指定的值。的迭代器返回到新的范围。被保留的元素的相对顺序.
原文:
Removing is done by shifting the elements in the range in such a way that elements to be erased are overwritten. The elements between the old and the new ends of the range have unspecified values. An iterator to the new end of the range is returned. Relative order of the elements that remain is preserved.
目录 |
[编辑] 参数
first, last | - | 元素的范围内进行处理
|
value | - | 要移除的元素的值
|
p | - | unary predicate which returns true 如果元素应该被删除 . The signature of the predicate function should be equivalent to the following: bool pred(const Type &a); The signature does not need to have const &, but the function must not modify the objects passed to it. |
类型要求 | ||
-ForwardIt 必须满足 ForwardIterator 的要求。
| ||
-The type of dereferenced ForwardIt must meet the requirements of MoveAssignable .
|
[编辑] 返回值
迭代器新的范围
[编辑] 复杂度
究竟std::distance(first, last)的谓词中的应用.
原文:
Exactly std::distance(first, last) applications of the predicate.
[编辑] 注释
类似的命名容器的成员函数list::remove,list::remove_if,forward_list::remove,forward_list::remove_if删除删除的元素.
原文:
The similarly-named container member functions list::remove, list::remove_if, forward_list::remove, and forward_list::remove_if erase the removed elements.
[编辑] 可能的实现
版本一 |
---|
template<class ForwardIt, class T> ForwardIt remove(ForwardIt first, ForwardIt last, const T& value) { ForwardIt result = first; for (; first != last; ++first) { if (!(*first == value)) { *result++ = *first; } } return result; } |
版本二 |
template<class ForwardIt, class UnaryPredicate> ForwardIt remove_if(ForwardIt first, ForwardIt last, UnaryPredicate p) { ForwardIt result = first; for (; first != last; ++first) { if (!p(*first)) { *result++ = *first; } } return result; } |
[编辑] 示例
下面的代码从一个字符串中删除所有的空格,将它们移动到结尾的字符串,然后删除.
原文:
The following code removes all spaces from a string by moving them to the end of the string and then erasing.
#include <algorithm> #include <string> #include <iostream> int main() { std::string str = "Text with some spaces"; str.erase(std::remove(str.begin(), str.end(), ' '), str.end()); std::cout << str << '\n'; }
输出:
Textwithsomespaces
[编辑] 另请参阅
复制一个范围内不满足特定条件的元素 (函数模板) |