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