Reputation: 7
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
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
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';
}
Upvotes: 1
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