ในบทเรียนนี้ เราจะอธิบาย partition_point ใน C++ STL
Partition Point คืออะไร?
partition_point คืน Iterator ชี้ไปที่ Element แรกใน Range ที่ Partitioned แล้ว ที่ Predicate เป็น False
ต้องใช้ร่วมกับ stable_partition หรือ partition ก่อน
ตัวอย่าง
#include <iostream>
#include <algorithm>
#include <vector>
bool IsOdd(int i) { return (i % 2) == 1; }
int main() {
vector<int> data = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
vector<int> odd, even;
// Partition: Odd ก่อน Even หลัง
stable_partition(data.begin(), data.end(), IsOdd);
// data = {1, 3, 5, 7, 9, 2, 4, 6, 8, 10}
// หาจุดแบ่ง
auto it = partition_point(data.begin(), data.end(), IsOdd);
// แยกเก็บ
odd.assign(data.begin(), it);
even.assign(it, data.end());
cout << "odd:";
for (int x : odd) cout << ' ' << x;
cout << '\n';
cout << "even:";
for (int x : even) cout << ' ' << x;
cout << '\n';
return 0;
}
ผลลัพธ์
odd: 1 3 5 7 9 even: 2 4 6 8 10
สรุป
partition/stable_partition= จัดกลุ่ม Element ตาม Predicatepartition_point= หาจุดแบ่งระหว่างกลุ่ม True/False- ต้องใช้ Predicate เดียวกับที่ Partition