This C++ program demonstrates the nth_element algorithm. The function rearranges the container elements in such a way that the element at the nth position is the element that would be in that position in a sorted sequence. The other elements are left without any specific order, except that none of the elements preceding nth are greater than it and none of the elements following it are less.
Here is the source code of the C++ program which demonstrates the nth_element algorithm. The C++ program is successfully compiled and run on a Linux system. The program output is also shown below.
/*
* C++ Program to demonstrate nth_element() algorithm
*/
#include <iostream>
#include <vector>
#include <algorithm>
#include <functional>
void print(const std::vector <int>& v)
{
std::vector <int>::const_iterator i;
for(i = v.begin(); i != v.end(); i++)
{
std::cout << *i << " ";
}
std::cout << std::endl;
}
int main()
{
std::vector<int> v;
for (int i = 0; i < 10; i++)
v.push_back((i + 3) % 10);
std::cout << "Vector : ";
print(v);
std::nth_element(v.begin(), v.begin() + 1, v.end(), std::greater<int>());
std::cout << "Vector with 6th element at its place, std::greater<int>() as predicate.\nVector : ";
print(v);
std::nth_element(v.begin(), v.begin() + 3, v.end(), std::less<int>());
std::cout << "Vector with 4th element at its place, std::less<int>() as predicate.\nVector : " ;
print(v);
}
$ a.out Vector : 3 4 5 6 7 8 9 0 1 2 Vector with 6th element at its place, std::greater<int>() predicate. Vector : 9 8 7 6 3 5 4 0 1 2 Vector with 4th element at its place, std::less<int>() predicate. Vector : 1 0 2 3 4 5 9 6 7 8
Sanfoundry Global Education & Learning Series – 1000 C++ Programs.
advertisement
advertisement
If you wish to look at all C++ Programming examples, go to C++ Programs.
If you find any mistake above, kindly email to [email protected]Related Posts:
- Practice Programming MCQs
- Practice Computer Science MCQs
- Apply for Computer Science Internship
- Apply for C++ Internship
- Check C++ Books