unique() Function in C++

This C++ program removes equal adjacent elements using unique() algorithm. The algorithm removes duplicate characters which are adjacent to each other in a container. The program creates an array of characters and runs the algorithm on the array. The array elements are then printed on the standard output.

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

$ 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.

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.