Skip to content
Related Articles

Related Articles

Improve Article

Remove duplicate elements in an Array using STL in C++

  • Difficulty Level : Easy
  • Last Updated : 17 Jun, 2019

Given an array, the task is to remove the duplicate elements from the array using STL in C++

Examples:

Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.  To complete your preparation from learning a language to DS Algo and many more,  please refer Complete Interview Preparation Course.

In case you wish to attend live classes with experts, please refer DSA Live Classes for Working Professionals and Competitive Programming Live for Students.

Input: arr[] = {2, 2, 2, 2, 2}
Output: arr[] = {2}

Input: arr[] = {1, 2, 2, 3, 4, 4, 4, 5, 5}
Output: arr[] = {1, 2, 3, 4, 5}

Approach:



This can be done using set in standard template library. Set type variable in STL automatically removes duplicating element when we store the element in it.

Below is the implementation of the above approach:




// C++ program to remove the
// duplicate elements from the array
// using STL in C++
  
#include <bits/stdc++.h>
using namespace std;
  
// Function to remove duplicate elements
void removeDuplicates(int arr[], int n)
{
  
    int i;
  
    // Initialise a set
    // to store the array values
    set<int> s;
  
    // Insert the array elements
    // into the set
    for (i = 0; i < n; i++) {
  
        // insert into set
        s.insert(arr[i]);
    }
  
    set<int>::iterator it;
  
    // Print the array with duplicates removed
    cout << "\nAfter removing duplicates:\n";
    for (it = s.begin(); it != s.end(); ++it)
        cout << *it << ", ";
    cout << '\n';
}
  
// Driver code
int main()
{
    int arr[] = { 4, 2, 3, 3, 2, 4 };
  
    int n = sizeof(arr) / sizeof(arr[0]);
  
    // Print array
    cout << "\nBefore removing duplicates:\n";
    for (int i = 0; i < n; i++)
        cout << arr[i] << " ";
  
    // call removeDuplicates()
    removeDuplicates(arr, n);
  
    return 0;
}
Output:
Before removing duplicates:
4 2 3 3 2 4 
After removing duplicates:
2, 3, 4,



My Personal Notes arrow_drop_up
Recommended Articles
Page :