C++ 序列操作之 partition 与 stable_partition

  1. partition 与 stable_partition 的详述

partition会将区间[first,last)中的元素重新排列,满足判断条件pred的元素会被放在区间的前段,不满足pred的元素会被放在区间的后段。该算法不能保证元素的初始相对位置,如果需要保证初始相对位置,应该使用stable_partition。

  1. 代码示例
bool IsOdd(int num)   //判断奇数
{
	return num & 1;   //num & 1 ; 是一个bool值:若为1,则num为奇数;若为0,则num为偶数。
}
int main()
{
    std::vector<int> ivec;
    for (int i = 1; i < 20; ++i)
        ivec.push_back(i); // 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19

    auto bound1 = stable_partition(ivec.begin(), ivec.end(), IsOdd);
    for (auto ite = ivec.begin(); ite != ivec.end(); ++ite)
    {
        cout << *ite << "  ";
    }
    cout << endl;
    cout << endl;

    auto bound = partition(ivec.begin(), ivec.end(), IsOdd); //partition与stable_partition的位置不同,输出的结果的顺序也就不同

    std::cout << "odd elements:";

    for (auto it = ivec.begin(); it != bound; ++it)
        cout << ' ' << *it;        

    cout << endl;


    cout << "even elements:";
    for (auto it = bound; it != ivec.end(); ++it)
        cout << ' ' << *it;   
    cout << endl;

	system("pause");
	return 0;

}

注:若想要看到不一样的输出结果,可调整bound与bound1对应行的代码位置!

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值