Since you turn on the vector at night, why not replace int *b=new int [n]; on std::vector<int> b(n) ? This also applies to freeing memory, you forgot delete[] b .
But, as others have already said, your solution will break if the array contains elements larger than n. A better approach might be counting elements with matching with int. That way, you can also count elements that cannot be used as an index to an array, such as a string.
There is also no reason to limit yourself to arrays. Here is a general solution that works with any container of any type, less comparable type:
#include <algorithm> #include <iterator> #include <map> struct by_second { template <typename Pair> bool operator()(const Pair& a, const Pair& b) { return a.second < b.second; } }; template <typename Fwd> typename std::map<typename std::iterator_traits<Fwd>::value_type, int>::value_type most_frequent_element(Fwd begin, Fwd end) { std::map<typename std::iterator_traits<Fwd>::value_type, int> count; for (Fwd it = begin; it != end; ++it) ++count[*it]; return *std::max_element(count.begin(), count.end(), by_second()); } #include <iostream> #include <vector> int main() { std::vector<int> test {1, 2, 3, 4, 4, 4, 5}; std::pair<int, int> x = most_frequent_element(test.begin(), test.end()); std::cout << x.first << " occured " << x.second << " times"; }
source share