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
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]

advertisement
advertisement
Subscribe to our Newsletters (Subject-wise). Participate in the Sanfoundry Certification contest 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
Manish Bhojasia, a technology veteran with 20+ years @ Cisco & Wipro, is Founder and CTO at Sanfoundry. He lives in Bangalore, and focuses on development of Linux Kernel, SAN Technologies, Advanced C, Data Structures & Alogrithms. Stay connected with him at LinkedIn.

Subscribe to his free Masterclasses at Youtube & discussions at Telegram SanfoundryClasses.