Print sorted distinct elements of array in C++

Given an array that might contain duplicates, print all distinct elements in sorted order.

Examples:

Input  : 1, 3, 2, 2, 1
Output : 1 2 3

Input  : 1, 1, 1, 2, 2, 3
Output : 1 2 3

Simple Solution is to sort the array first, then traverse the array and print only first occurrences of elements.

Another Approach is to use set in C++ STL.

[sourcecode language=”CPP”]
// CPP program to print sorted distinct
// elements.
#include <bits/stdc++.h>
using namespace std;

void printRepeating(int arr[], int size)
{
// Create a set using array elements
set<int> s(arr, arr + size);

// Print contents of the set.
for (auto x : s)
cout << x << " ";
}

// Driver code
int main()
{
int arr[] = { 1, 3, 2, 2, 1 };
int n = sizeof(arr) / sizeof(arr[0]);
printRepeating(arr, n);
return 0;
}
[/sourcecode]

Output:

1 2 3


My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.



Improved By : manishshaw1, shrikanth13



Article Tags :
Practice Tags :


Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.