I\'m looking for an elegant way of determining which element has the highest occurrence (mode) in a C++ ptr array.
For example, in
{\"pear\", \"apple
There are several possible solutions to that problem, but first some advice:
Don't use C-style arrays. Use std::array
for fixed (compiletime) size arrays or std::vector
for arrays on the heap (or C++14's std::dynarray
if the array size is determined at runtime but does not change after creation). Those containers do the memory management for you, and you do not need to pass the array size around separately. In addition to using containers, prefer to use the algorithms in <algorithm>
where appropiate. If you don't know the containers and algorithms, take some time to get familiar with them, that time will pay off very soon.
So, here are some solution sketches:
Sort the array, then count the ocurrences of consecutive values. It's much easier than to keep track of which values you have already counted and which not. You basically need only two value-count pairs: one for the value you are currently counting, one for the maximum count up to now. You will only need a fifth variable: the iterator for the container.
If you cannot sort your array or need to keep track of all counts, use a map to map values to their number of occurrence in the array. If you are familiar with std::map
, that is very simple to do. At the end, search for the maximum count, i.e. for the maximum map value:
for (auto i: students) countMap[i]++;
auto pos = std::max_element(begin(countMap), end(countMap),
[](auto lhs, auto rhs){ return lhs.second < rhs.second }); //! see below
auto maxCount = pos->second;
Note: this uses C++11's range based for and a C++14 polymorphic Lambda. It should be obvious what is done here, so it can be adjusted for the C++11/C++14 support your compiler provides.