count和count_if的区别和作用
时间: 2023-05-17 10:07:07 浏览: 73
count和count_if都是STL中的算法函数,用于统计指定范围内满足条件的元素个数。其中,count用于统计指定范围内等于某个值的元素个数,而count_if用于统计指定范围内满足某个条件的元素个数。具体使用方法如下:
count:
```c++
template<class InputIt, class T>
typename iterator_traits<InputIt>::difference_type
count(InputIt first, InputIt last, const T& value);
```
其中,first和last表示指定范围的起始和结束迭代器,value表示要统计的值。返回值为指定范围内等于value的元素个数。
count_if:
```c++
template<class InputIt, class UnaryPredicate>
typename iterator_traits<InputIt>::difference_type
count_if(InputIt first, InputIt last, UnaryPredicate p);
```
其中,first和last表示指定范围的起始和结束迭代器,p表示要满足的条件,可以是函数指针、函数对象或lambda表达式。返回值为指定范围内满足条件p的元素个数。
举个例子,假设有一个vector<int> v,我们要统计其中等于3的元素个数,可以使用count函数:
```c++
int n = count(v.begin(), v.end(), 3);
```
如果我们要统计其中大于等于5的元素个数,可以使用count_if函数:
```c++
int n = count_if(v.begin(), v.end(), [](int x){ return x >= 5; });
```
这样就可以得到满足条件的元素个数了。