Count frequencies of elements in array I've been writing code to get the frequencies of elements of an array. The code works, but it uses a lot of "old style" C constructs, some of which I feel should be changed to more C++-like features, but I don't know exactly which way would be best. In general, I feel that a lot of the code could be improved to be more elegant.

The first two functions, remdups and freq, are helper functions for getFrequencies, which is "facade" of the API.

#include &lt;stdio.h&gt;
#include &lt;stdlib.h&gt;
#include &lt;string.h&gt;
#include &lt;vector&gt;

template &lt;class T&gt; void remdups(T *arr, size_t *n)
{
    for (size_t i = 1; i &lt; *n; ) {
        if (arr[i] == arr[i-1]) {
            memmove(arr + i - 1, arr + i, (*n-i) * sizeof (T));
            --*n;
        } else
            ++i;
    }
}

int *freq(const int *arr, size_t n, size_t *outN)
{
    int *freq = new int[n], cnt;

    for (size_t i = *outN = 0; i &lt; n; ++i) {
        freq[i] = -1;
        cnt = 1;
        for (size_t j = i + 1; j &lt; n; ++j) {
            if (arr[i] == arr[j]) {
                ++cnt;
                freq[j] = 0;
            }
        }
        if (freq[i] != 0) {
            freq[i] = cnt;
            ++*outN;
        }
    }

    // remove duplicate frequency entries
    remdups&lt;int&gt;(freq, outN);
    return freq;
}

std::vector&lt;std::pair&lt;int, size_t&gt;&gt; getFrequencies(std::vector&lt;int&gt; arr)
{
    size_t n = arr.size(), newSize;
    int *freqs = freq(&amp;arr[0], n, &amp;newSize);

    // remove duplicate values from the array
    remdups(&amp;arr[0], &amp;newSize);

    std::vector&lt;std::pair&lt;int, size_t&gt;&gt; ret;

    for (size_t i = 0; i &lt; newSize; ++i)
        ret.push_back(std::pair&lt;int, size_t&gt; { arr[i], freqs[i] });

    delete []freqs;
    return ret;
}


Example driver code:

int main()
{
    std::vector&lt;int&gt; v = { 5, -3, -3, -3, -2, 0, 0 };
    auto freqs = getFrequencies(v);

    printf("%8s %8s\n", "Elem.", "Freq.");
    for (auto it = freqs.cbegin(); it != freqs.cend(); ++it)
        printf("%8d %8zu\n", it-&gt;first, it-&gt;second);
}
This seems over-complicated.  A simpler solution would use a std::map or std::unordered_map for the counting:

std::unordered_map&lt;int, std::size_t&gt; counts;
for (auto const &amp;element: container) {
     ++counts[element];
}




Instead of being tied to std::vector&lt;int&gt;, we could make the code much more flexible as a template, taking a pair of iterators (or, from C++20, a std::range) with any appropriate element type.  The signature might look something like:

template&lt;typename Iter&gt;
auto getFrequencies(Iter begin, Iter end)
   -&gt; std::unordered_map&lt;decltype(*Iter), std::size_t&gt;;


We might use constraints or SFINAE to choose whether to return an ordered or unordered map, based on whether *Iter is ordered and/or hashable.