c++ stl 中stable_patition使用方法(转)

如果要分类5个奇数,例如:
5
1 2 3 4 5
如果使用partition函数,那么输出不一定是:
1 3 5
2 4
也有可能是:
3 5 1
4 2

如果使用stable_partition函数(稳定整理算法),那么输出一定就是:
1 3 5
2 4

它保持了原来元素的顺序。
stable_patition接受三个参数,起始位置,终止位置和比较规则
关于分类奇数和偶数(stable_partition函数)的例题,代码:

#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
bool compare(int n){
    return n%2;
}
int main(){
    vector<int>v;
    int n;
    cin>>n;
    for(int i=1;i<=n;i++){
        v.push_back(i);
    }
    vector<int>::iterator it=stable_partition(v.begin(), v.end(), compare);
    vector<int>::iterator iter=v.begin();
    for(;iter!=it;iter++)
        cout<<*iter<<" ";
    cout<<endl;
    for(;it!=v.end();it++)
        cout<<*it<<" ";
    cout<<endl;
    return 0;
}

猜你喜欢

转载自www.cnblogs.com/maskoff/p/8903100.html