C++20 sections · 1024 units
Open in Course

Problem: Counting Occurrences

Practice with vectors

I'll teach you how to count how many times a value appears in a vector. Use the count function from algorithm with int freq = count(v.begin(), v.end(), target). This scans the entire vector and returns the number of matches.

For multiple targets, loop through each one and call count. If you need frequencies of all unique values, use a map instead. To count elements that match a condition like even numbers, use count_if(v.begin(), v.end(), [](int x) { return x % 2 == 0; }) with a lambda function that returns true for matches.