zoukankan      html  css  js  c++  java
  • 【STL源码剖析读书笔记】【第6章】算法之partition算法

    1、partition将区间[first, last)中的元素重新排列。所有被一元条件运算pred判定为true的元素,放在区间的前段,判定为false的元素,放在区间的后段。该算法并不保证元素的原始相对位置。

    2、partition源代码

    template <class BidirectionalIterator, class Predicate>
    BidirectionalIterator partition(BidirectionalIterator first,
    	BidirectionalIterator last, Predicate pred) {
    	while (true) {
    		while (true)
    			if (first == last)//头指针等于尾指针,所有操作结束
    				return first;
    			else if (pred(*first))//头指针所指元素不符合移动条件
    				++first;
    			else//头指针所指元素符合移动条件,跳出内循环
    				break;
    		--last;//尾指针减1
    		while (true)
    			if (first == last)//头指针等于尾指针,所有操作结束
    				return first;
    			else if (!pred(*last))//尾指针所指元素不符合移动条件
    				--last;
    			else//尾指针所指元素符合移动条件,跳出内循环
    				break;
    		iter_swap(first, last);//头尾指针所指元素彼此交换
    		++first;//头指针前进1,准备下一个外循环迭代
    	}
    }
    3、具体例子

    #include<iostream>
    #include<algorithm>
    using namespace std;
    
    template<typename T>
    struct isEven:public unary_function<T,bool>{
    	bool operator()(const T& x) const{
    		return x % 2 ? false : true;
    	}
    };
    int main(){
    	int ia[] = { 0, 1, 2, 3, 4, 4, 5, 5, 6, 6, 6, 6, 6, 7, 8 };
    	partition(begin(ia), end(ia), isEven<int>());
    	for (int* it = begin(ia); it != end(ia); ++it)
    		cout << *it << " ";
    	cout << endl;
    
    	system("pause");
    	return 0;
    }

    4、上述例子中partition工作过程



  • 相关阅读:
    hdu4273Rescue(三维凸包重心)
    hdu4449Building Design(三维凸包+平面旋转)
    hdu3847Trash Removal(凸包)
    CodeForces 166B (凸包)
    机器学习文章导航
    梯度下降法深入
    插值法
    离散系统频域分析
    离散系统时域分析
    连续系统频域分析
  • 原文地址:https://www.cnblogs.com/ruan875417/p/4558303.html
Copyright © 2011-2022 走看看