1 2 3 4 5 6 7 8 9
假设筛选条件为 i%2==0(也就是筛选出偶数),如果借助 stable_partition() 函数,则数组 a[10] 中元素的存储顺序会变成:2 4 6 8 1 3 5 7 9
而如果选用同样的筛选规则,使用 partition_copy() 函数还需要为其配备 2 个存储空间(例如 b[10] 和 c[10]),其中 b[10] 用于存储符合筛选条件的偶数,而 c[10] 用于存储不符合筛选条件的奇数,也就是说,partition_copy() 函数执行的最终结果为:
a[10]: 1 2 3 4 5 6 7 8 9
b[10]: 2 4 6 8
c[10]: 1 3 5 7 9
注意,这里仅展示了 b[10] 和 c[10] 数组中存储的有效数据。
<algorithm>
头文件中,其语法格式如下:pair<OutputIterator1,OutputIterator2> partition_copy ( InputIterator first, InputIterator last, OutputIterator1 result_true, OutputIterator2 result_false, UnaryPredicate pred);其中,各个参数的含义为:
#include <iostream> // std::cout #include <algorithm> // std::partition_copy #include <vector> // std::vector using namespace std; //以普通函数的方式定义筛选规则 bool mycomp(int i) { return (i % 2) == 0; } //以函数对象的形式定义筛选规则 class mycomp2 { public: bool operator()(const int& i) { return (i % 2 == 0); } }; int main() { vector<int> myvector{ 1,2,3,4,5,6,7,8,9 }; int b[10] = { 0 }, c[10] = { 0 }; //以 mycomp 规则,对 myvector 容器中的数据进行分组,这里的 mycomp 还可以改为 mycomp2(),即以 mycomp2 为筛选规则 pair<int*, int*> result= partition_copy(myvector.begin(), myvector.end(), b, c, mycomp); cout << "b[10]:"; for (int *p = b; p < result.first; p++) { cout << *p << " "; } cout << "\nc[10]:"; for (int *p = c; p < result.second; p++) { cout << *p << " "; } return 0; }程序执行结果为:
b[10]:2 4 6 8
c[10]:1 3 5 7 9
C++ 标准库中还给出了 partition_copy() 函数底层实现的参考代码,感兴趣的读者可自行研究,这里不再进行过多赘述。程序中仅演示了如何用数组来存储 partition_copy() 函数分组后的数据,当然也可以用容器来存储。
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); }
Copyright © 广州京杭网络科技有限公司 2005-2025 版权所有 粤ICP备16019765号
广州京杭网络科技有限公司 版权所有