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
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
using namespace std;
int main()
{
vector 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
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
要从最佳影片策划和实践问题去学习,检查了C++基础课程为基础,以先进的C++和C++ STL课程基础加上STL。要完成从学习语言到DS Algo等的更多准备工作,请参阅“完整面试准备课程” 。