std::count, std::count_if
来自cppreference.com
|
|
该页由英文版wiki使用Google Translate机器翻译而来。
该翻译可能存在错误或用词不当。鼠标停留在文本上可以看到原版本。你可以帮助我们修正错误或改进翻译。参见说明请点击这里. |
| 在头文件 <algorithm> 中定义
|
||
| template< class InputIt, class T > typename iterator_traits<InputIt>::difference_type |
(1) | |
| template< class InputIt, class UnaryPredicate > typename iterator_traits<InputIt>::difference_type |
(2) | |
返回的范围内的元素的数目
[first, last)满足特定条件。重要的元素是等于value的第一个版本,第二个版本计算元素的谓词p回报true. 原文:
Returns the number of elements in the range
[first, last) satisfying specific criteria. The first version counts the elements that are equal to value, the second version counts elements for which predicate p returns true. 目录 |
[编辑] 参数
| first, last | - | 检查的元素
|
| value | - | 要搜索的值
|
| p | - | 一元谓词 所需的元素 返回true. 谓词函数的签名形式如下: bool pred(const Type &a); 虽然函数签名中const &不是必须的,但是函数必须保证不会修改传递给它的对象。 |
| 类型要求 | ||
-InputIt 必须满足 InputIterator 的要求。
| ||
[编辑] 返回值
满足条件的元素的数量.
原文:
number of elements satisfying the condition.
[编辑] 复杂度
完全
last - first比较/应用程序的谓词原文:
exactly
last - first comparisons / applications of the predicate[编辑] 可能的实现
| 版本一 |
|---|
template<class InputIt, class T> typename iterator_traits<InputIt>::difference_type count(InputIt first, InputIt last, const T& value) { typename iterator_traits<InputIt>::difference_type ret = 0; for (; first != last; ++first) { if (*first == value) { ret++; } } return ret; } |
| 版本二 |
template<class InputIt, class UnaryPredicate> typename iterator_traits<InputIt>::difference_type count_if(InputIt first, InputIt last, UnaryPredicate p) { typename iterator_traits<InputIt>::difference_type ret = 0; for (; first != last; ++first) { if (p(*first)) { ret++; } } return ret; } |
[编辑] 示例
下面的代码使用
count,以确定如何在std::vector匹配多个整数目标值.
原文:
The following code uses
count to determine how many integers in a std::vector match a target value.
#include <algorithm> #include <iostream> #include <vector> int main() { int data[] = { 1, 2, 3, 4, 4, 3, 7, 8, 9, 10 }; std::vector<int> v(data, data+10); int target1 = 3; int target2 = 5; int num_items1 = std::count(v.begin(), v.end(), target1); int num_items2 = std::count(v.begin(), v.end(), target2); std::cout << "number: " << target1 << " count: " << num_items1 << '\n'; std::cout << "number: " << target2 << " count: " << num_items2 << '\n'; }
输出:
number: 3 count: 2 number: 5 count: 0
#include <algorithm> #include <iostream> #include <vector> int main() { int data[] = { 1, 2, 3, 4, 4, 3, 7, 8, 9, 10 }; std::vector<int> v(data, data+10); int num_items1 = std::count_if(v.begin(), v.end(), [](int i) {return i % 3 == 0;}); std::cout << "number divisible by three: " << num_items1 << '\n'; }
输出:
number divisible by three: 3