C ++ STLトピック

//实现求第k小元素、部分排序以及按条件划分
#include<bits/stdc++.h>
using namespace std;
bool cmp(int &a) 
{ 
	return a>5;   //按大于五的元素划分 
}  
int main()
{   
    vector<int>p;
    vector<int>::iterator it,end;
     it=p.begin(),end=p.end() ;
    for(int i=0;i<10;i++)    { p.push_back(i);} 
    random_shuffle(p.begin(),p.end());  //打乱数组元素 
    for(it=p.begin() ;it!=p.end() ;++it)   cout<<*it<<" ";  //进行操作前的序列 
    cout<<endl;  
    //要保证cmp的值返回为0  
    vector <int> ::iterator it1=partition(it,end,cmp); //按条件划分 (不稳定)
    //vector <int> ::iterator it1=stable_partition(it,end,cmp);//按条件划分 (稳定)
    for( ;it1!=p.end() ;++it1)   cout<<*it1<<" ";
    //求第k小元素 
    int k=5;
	nth_element(it,it+k,end);
	for(it=p.begin() ;it!=p.end() ;++it)   cout<<*it<<" ";
    return 0;
}  
リリース9件のオリジナルの記事 ウォンの賞賛0 ビュー98

おすすめ

転載: blog.csdn.net/weixin_44586132/article/details/103357489