partial_sort_copy() Function in C++

This C++ program demonstrates using partial_sort_copy() algorithm. The algorithm partially sorts the container elements and copies the sorted elements into another container according to the capacity of the second container.

Here is the source code of the C++ program which demonstrates using partial_sort_copy() algorithm. The C++ program is successfully compiled and run on a Linux system. The program output is also shown below.

  1. /*
  2.  * C++ Program to demonstrate the partial_sort_copy() algorithm
  3.  */
  4. #include <algorithm>
  5. #include <vector>
  6. #include <functional>
  7. #include <iostream>
  8. using namespace std; 
  9.  
  10. void print(vector<int> & v)
  11. {
  12.     vector<int>::iterator it;
  13.  
  14.     for (it = v0.begin(); it != v0.end(); it++) {
  15.         cout << *it << ' ';
  16.     }
  17.     cout << '\n';
  18. }
  19.  
  20. int main()
  21. {
  22.     vector<int> v0{4, 2, 5, 1, 3};
  23.     vector<int> v1{10, 11, 12};
  24.     vector<int> v2{10, 11, 12, 13, 14, 15, 16};
  25.  
  26.     cout << "v0 : ";
  27.     print(v0);
  28.  
  29.     cout << "v1 : ";
  30.     print(v1);
  31.  
  32.     cout << "v2 : ";
  33.     print(v2);
  34.  
  35.     it = partial_sort_copy(v0.begin(), v0.end(), v1.begin(), v1.end());
  36.  
  37.     cout << "Writing v0 to v1 in ascending order gives: ";
  38.     print(v1);
  39.  
  40.     it = partial_sort_copy(v0.begin(), v0.end(), v2.begin(), v2.end(), 
  41.                                 std::greater<int>());
  42.  
  43.     cout << "Writing v0 to v2 in descending order gives: ";
  44.     print(v2);
  45. }

$ gcc test.cpp
$ a.out
v0 : 4 2 5 1 3 
v1 : 10 11 12 
v2 : 10 11 12 13 14 15 16 
Writing v0 to v1 in ascending order gives: 1 2 3 
Writing v0 to v2 in descending order gives: 5 4 3 2 1 15 16

Sanfoundry Global Education & Learning Series – 1000 C++ Programs.

advertisement
If you wish to look at all C++ Programming examples, go to C++ Programs.

advertisement
Subscribe to our Newsletters (Subject-wise). Participate in the Sanfoundry Certification to get free Certificate of Merit. Join our social networks below and stay updated with latest contests, videos, internships and jobs!

Youtube | Telegram | LinkedIn | Instagram | Facebook | Twitter | Pinterest
Manish Bhojasia - Founder & CTO at Sanfoundry
I’m Manish - Founder and CTO at Sanfoundry. I’ve been working in tech for over 25 years, with deep focus on Linux kernel, SAN technologies, Advanced C, Full Stack and Scalable website designs.

You can connect with me on LinkedIn, watch my Youtube Masterclasses, or join my Telegram tech discussions.

If you’re in your 20s–40s and exploring new directions in your career, I also offer mentoring. Learn more here.