c++arraysfrequency

What is the fastest way to get the frequency of numbers in an array in C++?


My method creates an std::map<int, int> and populates it with the number and its frequency by iterating over the array once, but I'm wondering if there's a quicker way without using a map.


Solution

  • std::unordered_map<int,int> can count frequencies as well but its operator[] has complexity (cppreference):

    Average case: constant, worst case: linear in size.

    Compared to

    Logarithmic in the size of the container.

    with a std::map.

    When the maximum number is small you can use an array, and directly count:

     for (const auto& number : array) counter[number]++;
    

    Admittetly, all this has already been said in comments, so I'll also add this one: You need to measure. Complexity is only about asymptotic runtime, while for given input size a std::map can actually be faster.