// nth_element.cpp -- 2011-10-03-12.58
#include "stdafx.h"
#include <iostream>
#include <algorithm>
#include <vector>
#include <functional>
using std ::vector ;
using std ::greater ;
template<class T>
class Print
{
public:
void operator () (const T & t) const
{
std ::cout << t << " " ;
}
} ;
int _tmain(int argc, _TCHAR* argv[])
{
int arr1[] = {1, 5, 4, 3, 2, 6, 7, 8} ;
vector<int> vec1(arr1, arr1 + sizeof arr1 / sizeof (int)) ;
// nth_element (beg, nth, end) ;
// 操作前:[beg,end)标示输入序列.nth是指向输入序列某个位置的迭代器,可以是end.
// 操作后:确定输入序列中第(nth - beg + 1)小的元素的值.同时,小于或等于该值的元素被移动到
// 该值的前面.大于或等于该值的元素被移动到该值的后面.
// 返回值:无.
// 备注: nth>end将抛出异常.整个序列被排序为按照非降序排序.
nth_element(vec1.begin(), vec1.begin() + 5, vec1.end()) ;
for_each(vec1.begin(), vec1.end(), Print<int> ()) ;
std ::cout << std ::endl << *(vec1.begin() + 5) << std ::endl ;
// nth_element (beg, nth, end, greater<int> ()) ;
// 操作前:[beg,end)标示输入序列.nth是指向输入序列某个位置的迭代器,可以是end.greater<int> ()是二元函数对象.
// 操作后:确定输入序列中第(nth - beg + 1)大的元素的值.同时,大于或等于该值的元素被移动到
// 该值的前面.小于或等于该值的元素被移动到该值的后面.
// 返回值:无.
// 备注: nth>end将抛出异常.整个序列被排序为按照非升序排序.
nth_element(vec1.begin(), vec1.begin() + 5, vec1.end(), greater<int> ()) ;
for_each(vec1.begin(), vec1.end(), Print<int> ()) ;
std ::cout << std ::endl << *(vec1.begin() + 5) ;
std ::cin.get() ;
return 0 ;
}
nth_element
最新推荐文章于 2024-05-30 21:13:03 发布