一:功能
将区间内元素分成两组,满足判断条件的放到第一组,不满足条件的在第二组。返回第二组中的首元素位置
二:使用
#include <vector>
#include <algorithm>
#include <string>
#include <iostream>
struct ExamResult {
std::string student_name;
int score;
};
std::vector<ExamResult> get_results() {
return {
{"Student 1", 100}, {"Student 2", 90}, {"Student 3", 15}, {"Student 4", 40},
{"Student 5", 65}, {"Student 6", 75}, {"Student 7", 85}, {"Student 8", 30}
};
}
int main() {
std::vector<ExamResult> results = get_results();
auto pp = std::partition(results.begin(), results.end(),
[threshold = 49](const auto& r) {
return r.score >= threshold;
});
// process passing students
for (auto it = results.begin(); it != pp; ++it) {
std::cout << "[PASS] " << it->student_name << "\n";
}
std::cout << "\n";
// process failed students
for (auto it = pp; it != results.end(); ++it) {
std::cout << "[FAIL] " << it->student_name << "\n";
}
}
三:实现
#include <algorithm>
#include <forward_list>
#include <iostream>
#include <iterator>
#include <vector>
template<class ForwardIt, class UnaryPred>
ForwardIt my_partition(ForwardIt first, ForwardIt last, UnaryPred p)
{
first = std::find_if_not(first, last, p);
if (first == last)
return first;
for (auto i = std::next(first); i != last; ++i)
if (p(*i))
{
std::iter_swap(i, first);
++first;
}
return first;
}
template<class ForwardIt>
void quicksort(ForwardIt first, ForwardIt last)
{
if (first == last)
return;
auto pivot = *std::next(first, std::distance(first, last) / 2);
auto middle1 = my_partition(first, last, [pivot](const auto& em)
{
return em < pivot;
});
auto middle2 = my_partition(middle1, last, [pivot](const auto& em)
{
return !(pivot < em);
});
quicksort(first, middle1);
quicksort(middle2, last);
}
int main()
{
std::vector<int> v{0, 1, 2, 3, 4, 5, 6, 7, 8, 9};
std::cout << "Original vector: ";
for (int elem : v)
std::cout << elem << ' ';
auto it = std::partition(v.begin(), v.end(), [](int i) {return i % 2 == 0;});
std::cout << "\nPartitioned vector: ";
std::copy(std::begin(v), it, std::ostream_iterator<int>(std::cout, " "));
std::cout << "* ";
std::copy(it, std::end(v), std::ostream_iterator<int>(std::cout, " "));
std::forward_list<int> fl {1, 30, -4, 3, 5, -4, 1, 6, -8, 2, -5, 64, 1, 92};
std::cout << "\nUnsorted list: ";
for (int n : fl)
std::cout << n << ' ';
quicksort(std::begin(fl), std::end(fl));
std::cout << "\nSorted using quicksort: ";
for (int fi : fl)
std::cout << fi << ' ';
std::cout << '\n';
}