unique_copy() Function in C++

This C++ program demonstrates the unique_copy() algorithm. The function unique_copy() takes three iterators as parameters – iterators to the beginning and end of the container and iterator to the container or output stream where the unique elements would be copied. The program demonstrates the use of the algorithm which removes the adjacent duplicate characters in the container but doesn’t modify the container elements.

Here is the source code of the C++ program which demonstrates the unique_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 remove equal adjacent elements using unique_copy() algorithm
  3.  */
  4.  
  5. #include <iostream>
  6. #include <algorithm>
  7. #include <functional>
  8. #include <vector>
  9. #include <iomanip>
  10. #include <iterator>
  11. using namespace std;
  12.  
  13. void print(char a[], int N)
  14. {   
  15.     for(int i = 0; i < N; i++)
  16.     {
  17.         cout <<  a[i] << "  ";
  18.     }
  19.     cout << endl;
  20. }
  21.  
  22. int main()
  23. {
  24.     char a[] = {'a', 'a', 'a', 'e', 'c', 'd', 'd', 'e', 'e', 'e'};
  25.     int alen = sizeof(a) / sizeof(char);
  26.  
  27.     cout << "Characters : ";
  28.     print(a, alen);
  29.     cout << "Removing duplicate adjacent characters ... " << endl;
  30.     cout << "Characters : ";
  31.     std::unique_copy(a, a + alen, ostream_iterator<char>(cout, "  "));
  32.     cout << endl;
  33. }

$ a.out
Characters : a  a  a  e  c  d  d  e  e  e  
Removing duplicate adjacent characters ... 
Characters : a  e  c  d  e

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

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

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.