Count Frequency Using Map
C++
Medium
5 views
Problem Description
Count how many times each element appears.
Real Life: Vote counting, inventory management.
Step-by-Step Logic:
1. Use map to store element and its count
2. For each element, increment its count
3. Map automatically handles new elements
4. Print all frequencies
Official Solution
void stl_q9_frequency_map() {
vector<int> numbers = {1, 2, 2, 3, 1, 4, 2, 3, 1};
map<int, int> frequency;
// Count frequencies
for(int num : numbers) {
frequency[num]++;
}
// Print frequencies
cout << "Element frequencies:" << endl;
for(auto pair : frequency) {
cout << pair.first << " appears " << pair.second << " times" << endl;
}
}
Solutions (0)
No solutions submitted yet. Be the first!
No comments yet. Start the discussion!