STL演算法 ------ 根據第n個元素排序
阿新 • • 發佈:2019-01-01
1. nth_element( b, n, e ) 對n位置的元素進行比較,大的放後面,小的放前面,n必須是迭代器指向輸入的元素;
2. nth_element(b, n, e, p )
3.對比:partition() 演算法
#include <iostream> #include <algorithm> #include <iterator> #include <vector> #include <list> #include <deque> #include <functional> using namespace std; template<typename T> void Print(const T& t) { for(typename T::const_iterator itr=t.begin(); itr!=t.end(); ++itr) { cout<<*itr<<' '; }cout<<endl; } int main( int argc, char** argv ) { deque<int> deq; for(int i=3; i<=7; ++i) { deq.push_back(i); } for(int i=2; i<=6; ++i) { deq.push_back(i); } for(int i=1; i<=5; ++i) { deq.push_back(i); } Print(deq); nth_element(deq.begin(), deq.begin()+3, deq.end()); Print(deq); copy(deq.begin(), deq.begin()+4, ostream_iterator<int>(cout, " ")); cout<<endl; nth_element(deq.begin(), deq.end()-4, deq.end()); copy(deq.end()-4, deq.end(), ostream_iterator<int>(cout, " ")); cout<<endl; nth_element(deq.begin(), deq.begin()+3, deq.end(), greater<int>()); copy(deq.begin(), deq.begin()+4, ostream_iterator<int>(cout, " ")); cout<<endl; deque<int>::iterator pos; pos = partition(deq.begin(), deq.end(), bind2nd(less_equal<int>(), 3)); copy(deq.begin(), pos, ostream_iterator<int>(cout, " ")); return 0; }