nth_element

 
// 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 ;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值