STL stable_partition函数

STL stable_partition函数算法

STL 中 partition() 函数只负责对指定区域内的数据进行分组,并不保证各组中元素的相对位置不发生改变。而如果想在分组的同时保证不改变各组中元素的相对位置,可以使用 stable_partition() 函数。

也就是说,stable_partition() 函数可以保证对指定区域内数据完成分组的同时,不改变各组内元素的相对位置。

STL stable_partition函数详解

头文件

#include <algorithm>

语法

BidirectionalIterator stable_partition (BidirectionalIterator first, BidirectionalIterator last, UnaryPredicate pred);

参数

参数 描述
first 正向迭代器
last 正向迭代器
pred 用于自定义查找规则。该规则实际上是一个包含 2 个参数且返回值类型为 bool 的函数。

说明

其中,first 和 last 都为正向迭代器,其组合 [first, last) 用于指定该函数的作用范围;pred 用于指定筛选规则。

技术细节

stable_partition() 函数还会返回一个双向迭代器,其指向的是两部分数据的分界位置,更确切地说,指向的是第二组数据中的第 1 个元素。

案例

STL stable_partition函数

使用 STL stable_partition 函数筛选集合

#include <iostream> #include <algorithm> #include <vector> using namespace std; class mycomp { public: bool operator()(const int& i) { return (i%2 == 0); } }; int main() { cout << "嗨客网(www.haicoder.net)\n" << endl; std::vector<int> myvector{1,2,3,4,5,6,7,8,9}; std::vector<int>::iterator bound; bound = std::stable_partition(myvector.begin(), myvector.end(), mycomp()); for (std::vector<int>::iterator it = myvector.begin(); it != myvector.end(); ++it) { cout << *it << " "; } cout << "\nbound = " << *bound; cout << endl; return 0; }

我们在 Linux 下使用 g++ 进行编译,具体命令如下:

g++ stable_partition.cpp -std=c++11

编译后,我们直接运行生成的二进制文件 a.out,如下图所示:

19_STL stable_partition函数.png

可以看到,程序中借助 stable_partition() 对 myvector 容器中的数据进行了再加工,基于 mycomp() 筛选规则,能够被 2 整除的元素位于第 1 组,不能被 2 整除的元素位于第 2 组。

同时,parition() 函数会返回一个迭代器,通过观察程序的执行结果可以看到,该迭代器指向的是元素 5,同时也是第 2 组数据中的第 1 个元素。

STL stable_partition函数总结

在 STL 中 partition() 函数只负责对指定区域内的数据进行分组,并不保证各组中元素的相对位置不发生改变。而如果想在分组的同时保证不改变各组中元素的相对位置,可以使用 stable_partition() 函数。

也就是说,stable_partition() 函数可以保证对指定区域内数据完成分组的同时,不改变各组内元素的相对位置。