std::remove_copy, std::remove_copy_if
| 在标头 <algorithm> 定义
|
||
| template< class InputIt, class OutputIt, class T > OutputIt remove_copy( InputIt first, InputIt last, |
(1) | (C++20 起为 constexpr) |
| template< class ExecutionPolicy, class ForwardIt1, class ForwardIt2, class T > |
(2) | (C++17 起) |
| template< class InputIt, class OutputIt, class UnaryPred > OutputIt remove_copy_if( InputIt first, InputIt last, |
(3) | (C++20 起为 constexpr) |
| template< class ExecutionPolicy, class ForwardIt1, class ForwardIt2, class UnaryPred > |
(4) | (C++17 起) |
复制来自范围 [first, last) 的元素到从 d_first 开始的另一范围,省略满足特定判别标准的元素。
|
std::is_execution_policy_v<std::decay_t<ExecutionPolicy>> |
(C++20 前) |
|
std::is_execution_policy_v<std::remove_cvref_t<ExecutionPolicy>> |
(C++20 起) |
如果 *d_first = *first 非法 (C++20 前)*first 不可写入 d_first (C++20 起),那么程序非良构。
如果源范围与目标范围有重叠,那么行为未定义。
目录 |
[编辑] 参数
| first, last | - | 要复制的元素范围 |
| d_first | - | 目标范围的起始 |
| value | - | 不复制的元素的值 |
| policy | - | 所用的执行策略。细节见执行策略。 |
| 类型要求 | ||
-InputIt 必须满足老式输入迭代器 (LegacyInputIterator) 。
| ||
-OutputIt 必须满足老式输出迭代器 (LegacyOutputIterator) 。
| ||
-ForwardIt1, ForwardIt2 必须满足老式向前迭代器 (LegacyForwardIterator) 。
| ||
-UnaryPred 必须满足谓词 (Predicate) 。
| ||
[编辑] 返回值
指向最后被复制元素之后的迭代器。
[编辑] 复杂度
给定 N 为 std::distance(first, last):
对带有 ExecutionPolicy 的重载,ForwardIt1 的 value_type 不满足可移动构造 (MoveConstructible) 时会有性能开销。
[编辑] 异常
拥有名为 ExecutionPolicy 的模板形参的重载按下列方式报告错误:
- 如果作为算法一部分调用的函数的执行抛出异常,且
ExecutionPolicy是标准策略之一,那么调用 std::terminate。对于任何其他ExecutionPolicy,行为由实现定义。 - 如果算法无法分配内存,那么抛出 std::bad_alloc。
[编辑] 可能的实现
| remove_copy |
|---|
template<class InputIt, class OutputIt, class T> OutputIt remove_copy(InputIt first, InputIt last, OutputIt d_first, const T& value) { for (; first != last; ++first) if (!(*first == value)) *d_first++ = *first; return d_first; } |
| remove_copy_if |
template<class InputIt, class OutputIt, class UnaryPred> OutputIt remove_copy_if(InputIt first, InputIt last, OutputIt d_first, UnaryPred p) { for (; first != last; ++first) if (!p(*first)) *d_first++ = *first; return d_first; } |
[编辑] 示例
下列代码输出字符串并在过程中擦除井号 '#'。
#include <algorithm> #include <iomanip> #include <iostream> #include <iterator> #include <string> int main() { std::string str = "#返回#值#优化"; std::cout << "擦除前:" << std::quoted(str) << "\n"; std::cout << "擦除后:\""; std::remove_copy(str.begin(), str.end(), std::ostream_iterator<char>(std::cout), '#'); std::cout << "\"\n"; }
输出:
擦除前:#返回#值#优化 擦除后:返回值优化
[编辑] 缺陷报告
下列更改行为的缺陷报告追溯地应用于以前出版的 C++ 标准。
| 缺陷报告 | 应用于 | 出版时的行为 | 正确行为 |
|---|---|---|---|
| LWG 779 | C++98 | T 需要是可相等比较 (EqualityComparable) 的,但是 ForwardIt 的值类型不一定是 T
|
改成要求 *d_first = *first 合法 |
[编辑] 参阅
| 移除满足特定判别标准的元素 (函数模板) | |
| (C++11) |
将某一范围的元素复制到一个新的位置 (函数模板) |
| (C++11) |
复制一个范围,将各元素分为两组 (函数模板) |
| (C++20)(C++20) |
复制一个范围的元素,忽略满足特定判别标准的元素 (niebloid) |