Count distinct elements in an array | C ++ program to count all distinct elements in a given array ; First sort the array so that all occurrences become consecutive ; Traverse the sorted array ; Move the index ahead while there are duplicates ; Driver program to test above function
#include <algorithm> NEW_LINE #include <iostream> NEW_LINE using namespace std ; int countDistinct ( int arr [ ] , int n ) { sort ( arr , arr + n ) ; int res = 0 ; for ( int i = 0 ; i < n ; i ++ ) { while ( i < n - 1 && arr [ i ] == arr [ i + 1 ] ) 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 ; }