std::remove_copy_if() 算法
- 自 C++20 起
- 自 C++17 起
- C++17 之前
// (1)
template< class InputIt, class OutputIt, class UnaryPredicate >
constexpr OutputIt remove_copy_if( InputIt first, InputIt last,
OutputIt d_first, UnaryPredicate p );
// (2)
template< class ExecutionPolicy, class ForwardIt1,
class ForwardIt2, class UnaryPredicate >
ForwardIt2 remove_copy_if( ExecutionPolicy&& policy,
ForwardIt1 first, ForwardIt1 last,
ForwardIt2 d_first, UnaryPredicate p );
// (1)
template< class InputIt, class OutputIt, class UnaryPredicate >
OutputIt remove_copy_if( InputIt first, InputIt last,
OutputIt d_first, UnaryPredicate p );
// (2)
template< class ExecutionPolicy, class ForwardIt1,
class ForwardIt2, class UnaryPredicate >
ForwardIt2 remove_copy_if( ExecutionPolicy&& policy,
ForwardIt1 first, ForwardIt1 last,
ForwardIt2 d_first, UnaryPredicate p );
// (1)
template< class InputIt, class OutputIt, class UnaryPredicate >
OutputIt remove_copy_if( InputIt first, InputIt last,
OutputIt d_first, UnaryPredicate p );
-
(1) 忽略谓词
p
返回true
的所有元素。 -
(2) 与 (1) 相同,但根据
policy
执行。重载决议只有在
std::is_execution_policy_v<std::decay_t<ExecutionPolicy>>
(C++20 之前)std::is_execution_policy_v<std::remove_cvref_t<ExecutionPolicy>>
(C++20 起) 为true
时,这些重载才参与重载决议。
- 自 C++11 起
- 直到 C++11
移除是通过移动(通过复制赋值 (C++11 之前) 移动赋值 (C++11 起))范围内的元素,使得不需要移除的元素出现在范围的开头。
保留其余元素的相对顺序,且容器的物理大小不变。
参数
first last | 要复制的元素范围。 |
d_first | 目标范围的开头。 |
policy | 要使用的执行策略。有关详细信息,请参阅执行策略。 |
p | 一元谓词,如果元素应该被忽略,则返回 对于类型为(可能为 const) |
类型要求
InputIt | LegacyInputIterator |
OutputIt | LegacyOutputIterator |
ForwardIt1 ForwardIt2 | LegacyForwardIterator |
Predicate | UnaryPredicate |
返回值
指向复制的最后一个元素之后元素的迭代器。
复杂度
给定 N
为 std::distance(first, last)
谓词 p
恰好应用 N 次。
异常
带有模板参数 ExecutionPolicy
的重载报告错误如下
- 如果作为算法一部分调用的函数执行时抛出异常且
ExecutionPolicy
是标准策略之一,则调用std::terminate
。对于任何其他ExecutionPolicy
,行为是实现定义的。. - 如果算法未能分配内存,则抛出
std::bad_alloc
。
可能的实现
remove_copy_if (1)
template<class InputIt, class OutputIt, class UnaryPredicate>
OutputIt remove_copy_if(InputIt first, InputIt last, OutputIt d_first, UnaryPredicate 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 = "#Return #Value #Optimization";
std::cout << "before: " << std::quoted(str) << '\n';
std::cout << "after: \"";
std::remove_copy(str.begin(), str.end(),
std::ostream_iterator<char>(std::cout), '#');
std::cout << "\"\n";
}
before: "#Return #Value #Optimization"
after: "Return Value Optimization"