count()函数stl
C ++ STL std:count()函数 (C++ STL std:count() function)
The C++ STL contains the function std::count(), which is used to find the occurrence of the particular element in the given range. You can use this function with an array, string, vector, etc.
C ++ STL包含函数std :: count() ,该函数用于查找给定范围内特定元素的出现。 您可以将此函数与数组,字符串,向量等一起使用。
To use this function, we have to use either <bits/stdc++> header or <algorithm> header.
要使用此功能,我们必须使用<bits / stdc ++>标头或<algorithm>标头。
Syntax of std::count() function:
std :: count()函数的语法:
count( start_point , end_point , val/element);
Parameters:
参数:
start_point: from where we want to start searching or the initial position.
start_point:从我们要开始搜索的位置或初始位置。
end_ point: ending point till where you want to search the element or the final position.
end_ point:直到要搜索元素或最终位置的终点。
val/elements: value or the element to be searched.
val / elements:值或要搜索的元素。
Return value: It returns the numbers of occurrences of the element in the given range.
返回值:返回给定范围内元素的出现次数。
For example:
例如:
If the given string is:
str="Includehelpisthebesttechenicalcontentplace"
Then if we count no of 'e's:
i.e.
count(str.begin(), str.end(), 'e');
Output: 8
Exceptions:
例外情况:
It throws exception when the element assignment is not proper or the iterator is out of range.
当元素分配不正确或迭代器超出范围时,它将引发异常。
In case of invalid parameters shows the undefined behaviors.
如果参数无效,则显示未定义的行为。
Time Complexity:
时间复杂度:
O(n) is the time complexity of the std::count() function as it follows searching.
O(n)是std :: count()函数在搜索之后的时间复杂度 。
Input Output format:
输入输出格式:
Input:
arr[] = { 3, 2, 1, 3, 3, 5, 3 };
n = sizeof(arr) / sizeof(arr[0]);
count(arr, arr + n, 3);
Output:
4
Input:
str = "includehelp";
count(str.begin(), str.end(), 'e');
Output:
2
C ++程序演示std :: count()函数的示例 (C++ program to demonstrate example of std::count() function)
/*
C++ program to count the number of occurences of
particular element in array ,string, vector,etc.
*/
#include<bits/stdc++.h>
using namespace std;
int main()
{
//declaration of integer array arr
int arr[]={2,3,5,3,5,6,3,5,5,5,5,4,5,3,6,7};
int s =sizeof(arr)/sizeof(arr[0]);
//declaration of vector container n
vector<int> n={1,2,3,4,2,2,2,5,5,3,2,2,2,7,2};
// take a string str
string str ="anagramandanagram";
//Here, we search the count of 5 in the array arr
//you may change it also 2,3,6 ...as wish
cout << "Number of times 5 appears :";
cout << count(arr, arr + s, 5);
//Here, we search the count of 2 in the vector n
//you may change it also 5,3,6... as wish
cout << "\n\nNumber of times 2 appears : ";
cout<<count(n.begin(), n.end(), 2);
//Here, we search the count of 'a' in the string str
//you may change it also b,c,d.. as wish
cout << "\n\nNumber of times 'a' appears : ";
cout << count(str.begin(), str.end(), 'a');
return 0;
}
Output
输出量
Number of times 5 appears :7
Number of times 2 appears : 8
Number of times 'a' appears : 7
翻译自: https://www.includehelp.com/stl/std-count-function-with-example-in-cpp-stl.aspx
count()函数stl