std::count()返回给定范围内元素的出现次数。返回[first,last)范围内等于val的元素数。
// Returns count of occurrences of value in
// range [begin, end]
int count(Iterator first, Iterator last, T &val)first, last:Input iterators to the initial and final positions of the sequence of elements.
val: Value to match
复杂度复杂度为O(n)的顺序。将每个元素与特定值进行一次比较。
计算数组中的出现次数。
// C++ program for count in C++ STL for
// array
#include <bits/stdc++.h>
using namespace std;
int main()
{
int arr[] = { 3, 2, 1, 3, 3, 5, 3 };
int n = sizeof(arr) / sizeof(arr[0]);
cout << "Number of times 3 appears:"
<< count(arr, arr + n, 3);
return 0;
}
Number of times 3 appears:4
计算向量中的出现次数。
// C++ program for count in C++ STL for
// a vector
#include <bits/stdc++.h>
using namespace std;
int main()
{
vector<int> vect{ 3, 2, 1, 3, 3, 5, 3 };
cout << "Number of times 3 appears:"
<< count(vect.begin(), vect.end(), 3);
return 0;
}
Number of times 3 appears:4
计算字符串中的出现次数。
// C++ program for the count in C++ STL
// for a string
#include <bits/stdc++.h>
using namespace std;
int main()
{
string str = "geeksforgeeks";
cout << "Number of times 'e' appears:"
<< count(str.begin(), str.end(), 'e');
return 0;
}
Number of times 'e' appears:4
相关用法
注:本文由纯净天空筛选整理自 std::count() in C++ STL。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。