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。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。