Rogue Wave banner
Previous fileTop of documentContentsIndexNext file

nth_element


Algorithm

Summary

Rearranges a collection so that all elements lower in sorted order than the nth element come before it and all elements higher in sorter order than the nth element come after it.

Data Type and Member Function Indexes
(exclusive of constructors and destructors)

None

Synopsis

#include <algorithm>
template <class RandomAccessIterator>
 void nth_element (RandomAccessIterator first,
                   RandomAccessIterator nth,
                   RandomAccessIterator last);

template <class RandomAccessIterator, class Compare>
 void nth_element (RandomAccessIterator first,
                   RandomAccessIterator nth,
                   RandomAccessIterator last,
                   Compare comp);

Description

The nth_element algorithm rearranges a collection according to either the default comparison operator (>) or a comparison operator given by the user. After the algorithm is applied, three things are true:

That is, for any iterator i in the range [first, nth) and any iterator j in the range [nth, last), it holds that !(*i > *j) or comp(*i, *j) == false.

Note that the elements that precede or follow the nth position are not necessarily sorted relative to each other. The nth_element algorithm does not sort the entire collection.

Complexity

The algorithm is linear, on average, where N is the size of the range [first, last).

Example

Program Output

Warnings

If your compiler does not support default template parameters, then you always need to supply the Allocator template argument. For instance, you need to write:

vector<int, allocator<int> >

instead of:

vector<int>

If your compiler does not support namespaces, then you do not need the using declaration for std.

See Also

Algorithms



Previous fileTop of documentContentsIndexNext file
©Copyright 1998, Rogue Wave Software, Inc.
Send mail to report errors or comment on the documentation.
OEM Release, June 1998