c++ nth_element用法

nth_element實際上就是快速選擇算法的實現,快速選擇算法實現原理具體見這裏

它是STL裏面的函數,使用時需要包含頭文件<algorithm>

void nth_element (Iterator first, Iterator first+nth, Iterator last, Compare comp);

重新排列range [first,last)中的元素,使第n個位置的元素是按排序順序在該位置的元素。
其他元素沒有任何特定的順序,只是第n個元素之前的元素都不大於該元素,而第n個元素後面的元素均不小於該元素。

#include <iostream>     // std::cout
#include <algorithm>    // std::nth_element, std::random_shuffle
#include <vector>       // std::vector
#include<iomanip>

using namespace std;

bool myfunction (int i,int j) { return (i>j); }

int main() {
	std::vector<int> myvector ;

	// set some values:
	for (int i = 0; i < 100; i++) myvector.push_back(i);   

	std::random_shuffle(myvector.begin(), myvector.end());

	// using default comparison (operator <):
	std::nth_element(myvector.begin(), myvector.begin() + 50, myvector.begin()+100);

	// using function as comp
	//std::nth_element(myvector.begin(), myvector.begin() +10, myvector.end(), myfunction);

	// print out content:
	std::cout << "myvector contains:";
	for (std::vector<int>::iterator it = myvector.begin(); it != myvector.end(); ++it)

	{
		if ((it - myvector.begin()) % 10 == 0)std::cout << endl;
		std::cout << setw(5) << *it;
		
	}
		
	std::cout << '\n';

	return 0;
}

輸出:

我這裏不知爲何,數字少了輸出結構和直接排序一樣,所以就用了100個數。在第50個位置,即myvector[49]處的元素未第50大的數(即49) ,49之前的數全部小於49,之後的數全部大於49。這種算法也可以用來找第k大的數。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章