I have a STL multiset
and I want to get the number of the elements that appears most in it
is there any existent function or method
for example, in a multiset, the elements are
1 3 3 3 4 4 4 4 5 5
then the elements that appears most is 4
and the number of 4's in the multiset is 5
so I will get 5
You can use the std::multiset::count method which returns the count for a specific key. You'll have to iterate over the keys, keeping track of the max count and the key associated with it.
I suggest a combination of what shacktar and LB suggested. After you build your multiset, count the elements and store the results in a std::map<int, int>. Also store the mode. You have to do this only once. Now, every time you change your set, modify the frequency map and, if necessary, change the mode. Does this look good?
EDIT: In fact, maybe a map is a better container for your data in the first place...
Since a multiset is a sequenced container just as a map is, there is no need to store both a multiset of values and a map of counts. If you only stored a map of (value,count), you can easily reconstruct the multiset by performing an in-order walk of the map.
Walking the map to find the most common value will be more efficient than walking the multiset, particularly if there are many duplicates. However, if that isn't fast enough, you can consider using a boost::multi_index_container where the first index is your map/multiset sort criterion and the second is on the count.
What would be wrong with treating the multiset as an array and iterating through it with two loops comparing each element with element[0], then each element with element[1] and so on, counting the repeats. You would not need to sort the set either. It doesn`t seem to be overly slow?