STL:划分与排序--2

partition(beg, end, unaryPred)

template <class ForwardIterator, class UnaryPredicate>
  ForwardIterator partition (ForwardIterator first,
                             ForwardIterator last, UnaryPredicate pred);

功能

容器中的元素作为unarypred函数的参数,返回true,将元素放在容器的前面;返回false,将元素放在容器的后半部分,从而实现划分。这里的划分是不稳定的,函数的原理是基于快速排序的思想,通过交换。

参数

[first,last),first为首迭代器,last为为迭代器,pred是一个一元参数(参数即迭代器里的元素)的函数,返回bool类型。

返回值

边界的迭代器,即第二部分的起始位置

stable_partition(beg, end, unaryPred)

 实现功能一样,只是算法是稳定的。

参考代码:

#include <iostream>//std::cout

#include<algorithm>//partition¨

#include<vector>//vector
using namespace std;

bool isOdd(int e){
	return (e%2)==1;
}
int main(int argc,char** argv){
   vector<int> myVector;
   for(int i=1;i<10;i++){
	myVector.push_back(i);
   }
   //output the elements in the vector
   for(vector<int>::iterator iter=myVector.begin();iter!=myVector.end();iter++){
	  cout<<*iter<<" ";
   }
   cout<<endl;
   //partition
	vector<int>::iterator bound;
	bound=partition(myVector.begin(),myVector.end(),isOdd);

   //stable_partition
   // bound=stable_partition(myVector.begin(),myVector.end(),isOdd);


	//output the result
	for(vector<int>::iterator iter=myVector.begin();iter!=bound;iter++){
		cout<<*iter<<" ";
	}
	cout<<endl;
	for(vector<int>::iterator iter=bound;iter!=myVector.end();iter++){
			cout<<*iter<<" ";
	}
		cout<<endl;
	return 0;
}

运行结果:显然不是稳定的

稳定算法运行结果

发布了53 篇原创文章 · 获赞 3 · 访问量 3498

猜你喜欢

转载自blog.csdn.net/sinat_38292108/article/details/103783216