| CARVIEW |
Select Language
HTTP/2 200
date: Tue, 30 Dec 2025 13:50:10 GMT
content-type: text/html; charset=utf-8
server: cloudflare
last-modified: Mon, 05 Jul 2021 23:22:32 GMT
vary: Accept-Encoding
access-control-allow-origin: *
nel: {"report_to":"cf-nel","success_fraction":0.0,"max_age":604800}
expires: Tue, 30 Dec 2025 14:00:10 GMT
cache-control: max-age=600
report-to: {"group":"cf-nel","max_age":604800,"endpoints":[{"url":"https://a.nel.cloudflare.com/report/v4?s=VO%2BbqoyAoBRTgPSkr5pmNpa%2BKF0zPQMACw85wKX3yDsE9Fu92yFIplGGOjMGLui9N9554NtHeRnxHYt6XJir%2BRpdwSls4r8EWzD2jw4kcg%3D%3D"}]}
x-proxy-cache: MISS
x-github-request-id: 2B61:D8C2:5E2AC5C:69D7CA0:6953D891
cf-cache-status: DYNAMIC
content-encoding: gzip
cf-ray: 9b62012d2da647c9-BOM
alt-svc: h3=":443"; ma=86400
Count occurrences of value in a range - C++ Patterns
← Patterns
Count occurrences of value in a range
123456789101112 | # include <iostream>
# include <algorithm>
# include <vector>
int main()
{
std::vector<int> numbers = {1, 2, 3, 5, 6, 3, 4, 1};
int count = std::count(std::begin(numbers),
std::end(numbers),
3);
} |
This pattern is licensed under the CC0 Public Domain Dedication.
Requires
c++98
or newer.
Intent
Count the number of occurrences of a particular value in a range of elements.
Description
On line 7, we create a std::vector of int
initialized with some values.
On lines 9–11, we use the alrogithm std::count,
to count the occurrences of a particular value in the std::vector.
For the first two arguments on lines 9–10, we use std::begin
and std::end to get the begin and end
iterators for the range in which we wish to count. The third
argument on line 11 is the value to count the occurrences of.
To count elements according to a predicate, you can use
std::count_if instead.