Count distinct elements in an array | CPP program to print all distinct elements of a given array ; This function prints all distinct elements ; Creates an empty hashset ; Traverse the input array ; If not present , then put it in hashtable and increment result ; Driver program to test above function
#include <bits/stdc++.h> NEW_LINE using namespace std ; int countDistinct ( int arr [ ] , int n ) { unordered_set < int > s ; int res = 0 ; for ( int i = 0 ; i < n ; i ++ ) { if ( s . find ( arr [ i ] ) == s . end ( ) ) { s . insert ( arr [ i ] ) ; res ++ ; } } return res ; } int main ( ) { int arr [ ] = { 6 , 10 , 5 , 4 , 9 , 120 , 4 , 6 , 10 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; cout << countDistinct ( arr , n ) ; return 0 ; }