algorithm - STL C++

nth_element()

Declaration

template <class RandomAccessIterator>
void nth_element(
	RandomAccessIterator  xFirst,
	RandomAccessIterator  xNth,
	RandomAccessIterator  xLast
);

Description

This function partitions the elements in range from "xFirst" up through the one before "xLast" so that the element at "xNth" is in its correct place. The elements before "xNth" are less than or equal to the element at "xNth" and the elements after "xNth" are greater than or equal it. The overloaded version uses the function "xComp" as a comparison function.

Header Include

#include <algorithm>

Overloads

template <class RandomAccessIterator, class BinaryPred>
void nth_element(
	RandomAccessIterator  xFirst,
	RandomAccessIterator  xNth,
	RandomAccessIterator  xLast,
	BinaryPred xComp
);

Example

#include <iostream>
#include <vector>
#include <algorithm>

int main()
{
	using namespace std;

	// Create a vector instance
	vector<int> qV;
	for (int i = 0; i < 20; i += 2) {
		qV.push_back(20 - i);
	}

	vector<int>::iterator qIter;
	// Output the vector
	cout << "The Vector: ";
	for (qIter = qV.begin(); qIter != qV.end(); ++qIter) {
		cout << *qIter << "  ";
	}
	cout << endl;

	// Partition the vector
	nth_element(qV.begin(), qV.begin() + 4, qV.end());

	// Output the partitioned vector
	cout << "The Result: ";
	for (qIter = qV.begin(); qIter != qV.end(); ++qIter) {
		cout << *qIter << "  ";
	}
	cout << endl;

	// Keep the window open
	cin.get();
	return 0;
}

Output

nth_element() Output
 

© 2007–2024 XoaX.net LLC. All rights reserved.