std::
partition_copy
函数模板 <algorithm>
template <class InputIterator, class OutputIterator1,
class OutputIterator2, class UnaryPredicate pred>
pair<OutputIterator1,OutputIterator2>
partition_copy (InputIterator first, InputIterator last,
OutputIterator1 result_true, OutputIterator2 result_false,
UnaryPredicate pred); |
对范围分区复制
将pred返回true的范围[first,last)中的元素复制到result_true所指向的范围内,
并将pred不返回true的元素复制到result_false所指向的范围内。
这个函数模板的行为相当于:
template <class InputIterator, class OutputIterator1,
class OutputIterator2, class UnaryPredicate pred>
pair<OutputIterator1,OutputIterator2>
partition_copy (InputIterator first, InputIterator last,
OutputIterator1 result_true, OutputIterator2 result_false,
UnaryPredicate pred)
{
while (first!=last) {
if (pred(*first)) {
*result_true = *first;
++result_true;
}
else {
*result_false = *first;
++result_false;
}
++first;
}
return std::make_pair (result_true,result_false);
} |
☲ 参数
-
first, last
-
指向要进行复制分区的序列的初始和最终位置的输入迭代器。
使用的范围是[first,last),
它包含first和last之间的所有元素,包括first指向的元素,但不包括last指向的元素。
-
result_true
-
指向pred返回true的元素存储范围的初始位置的输出迭代器。
-
result_false
-
指向pred返回false的元素存储范围的初始位置的输出迭代器。
-
pred
-
一个一元函数,它接受范围中的一个元素作为参数,并返回一个可转换为bool的值。
返回的值指示复制元素到哪个结果范围内。
函数不应修改其参数。
它可以是函数指针,也可以是函数对象。
范围不得重叠。
输出迭代器类型所指向的类型应支持对[first,last)范围内的元素赋值。
☉ 返回值
一个迭代器的pair,分别指向生成序列result_true和result_false的末端。
它的成员first 指向被复制到pred返回true的元素序列的最后一个元素之后的元素。
它的成员second 指向被复制到pred返回false的元素序列的最后一个元素后面的元素。
☣ 示例
// partition_copy example
#include <iostream> // std::cout
#include <algorithm> // std::partition_copy, std::count_if
#include <vector> // std::vector
bool IsOdd (int i) { return (i%2)==1; }
int main () {
std::vector<int> foo {1,2,3,4,5,6,7,8,9};
std::vector<int> odd, even;
// resize vectors to proper size:
unsigned n = std::count_if (foo.begin(), foo.end(), IsOdd);
odd.resize(n); even.resize(foo.size()-n);
// partition:
std::partition_copy (foo.begin(), foo.end(), odd.begin(), even.begin(), IsOdd);
// print contents:
std::cout << "odd: "; for (int& x:odd) std::cout << ' ' << x; std::cout << '\n';
std::cout << "even: "; for (int& x:even) std::cout << ' ' << x; std::cout << '\n';
return 0;
} |
输出:
odd: 1 3 5 7 9
even: 2 4 6 8
✥ 复杂度
first and last之间的距离为线性:调用pred并对每个元素执行一次赋值。
⇄ 数据竞争
[first,last)范围内的对象被访问(每个对象只访问一次)。
在result_true和result_false所指向的范围内,
直到返回的迭代器所指向的元素为止的对象都被修改(每个只修改一次)。
☂ 异常安全性
如果pred、元素赋值或迭代器上的任何操作抛出,则抛出。
注意,无效的参数会导致未定义的行为。
🍄 另请参阅
partition |
对范围分区 (函数模板) |
stable_partition |
对范围稳定有序分区(函数模板) |
is_partitioned |
测试是否对范围进行了分区(函数模板) |
partition_point |
获取分区点(函数模板) |