Niraj singh
Niraj singh

Reputation: 7

c++ How to count element frequency smartly?

I am getting array element [2 2 2 3 4 5 6] I want the count of each element stored ? How to do in best way stl or something like that?

Upvotes: 0

Views: 1186

Answers (3)

Caleth
Caleth

Reputation: 63019

If you know that the possible range of values is small and near 0:

std::array<size_t, max_value> histogram;

Otherwise

std::/*unordered_*/map<int, size_t> histogram;

And then

for (int value : elements) { ++histogram[value]; }

Upvotes: 2

Marek R
Marek R

Reputation: 38062

std::unordered_map<int, size_t> histogram;

for (auto a : table) {
    ++histogram[a];
}

for(auto [val, count] : histogram) {
    std::cout << val << ' ' << count << '\n';
}

https://godbolt.org/z/avo6Wo

Upvotes: 1

Fureeish
Fureeish

Reputation: 13434

Use std::map:

int main() {
    std::vector<int> vec = {2, 2, 2, 3, 4, 5, 6};

    std::map<int, int> occurrences;
    for (auto i : vec) occurrences[i]++;

    for (auto [element, count] : occurrences) {
        std::cout << element << " appeared " << count << " times\n";
    }
}

Upvotes: 2

Related Questions