I need to count the similar elements in an array. For example, if i have an array,
array[0,0,0,1,2,3,3].The number of 0’s are 3 , no. of 1’s are 1 , no. of 2’s are 1 , no. of 3’s are 2 in this array . I am sorry if this message has been posted before. Help is appreciated. Thanks in advance.
Regards,
THM
P.S : Language is C/C++
I can think of a few options:
Copy the array into a
std::multiset<>and then use thecount()orequal_range()member functions to return the countsCreate a
std::map<T,unsigned>. The map key (of your array entry typeT, which will be an integral type from your example) is the array entry, the value is the count. Increment the count associated with a value every time you encounter an element with that value as you iterate through the arrayIf the array is sorted use
std::equal_range()to find consecutive equal elements, and count them.There are of course many more, including just iterating though and counting directly.