一:功能
对区间内的元素进行分组,将分组结果拷贝到给定序列中。
二:用法
#include <vector>
#include <algorithm>
#include <iostream>int main() {std::vector<int> data{2, 4, 6, 1, 3, 5};auto is_even = [](int v) { return v % 2 == 0; };std::vector<int> even, odd;std::partition_copy(data.begin(), data.end(),std::back_inserter(even),std::back_inserter(odd),is_even);std::cout << "even == ";for (auto v : even) {std::cout << v << " ";}std::cout << "\n";std::cout << "odd == ";for (auto v : odd) {std::cout << v << " ";}std::cout << "\n";
}
三:实现
#include <algorithm>
#include <iostream>
#include <utility>template<class InputIt, class OutputIt1,class OutputIt2, class UnaryPred>
constexpr //< since C++20
std::pair<OutputIt1, OutputIt2>my_partition_copy(InputIt first, InputIt last,OutputIt1 d_first_true, OutputIt2 d_first_false,UnaryPred p)
{for (; first != last; ++first){if (p(*first)){*d_first_true = *first;++d_first_true;}else{*d_first_false = *first;++d_first_false;}}return std::pair<OutputIt1, OutputIt2>(d_first_true, d_first_false);
}void print(auto rem, const auto& v)
{for (std::cout << rem; const auto& x : v)std::cout << x << ' ';std::cout << '\n';
}int main()
{int arr[10] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9};int true_arr[5] = {0};int false_arr[5] = {0};my_partition_copy(std::begin(arr), std::end(arr),std::begin(true_arr), std::begin(false_arr),[](int i) { return 4 < i; });print("true_arr: ", true_arr);print("false_arr: ", false_arr);
}