c++ algorithm之count_if
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了c++ algorithm之count_if,小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含1573字,纯文字阅读大概需要3分钟。
内容图文
函数原型:
template <class InputIterator, class UnaryPredicate> typename iterator_traits<InputIterator>::difference_type count_if (InputIterator first, InputIterator last, UnaryPredicate pred);
功能:
在范围内返回满足条件元素的个数。
返回范围[first, last)范围内是pred为true的元素个数。
函数的行为与以下函数相等:
template <class InputIterator, class UnaryPredicate> typename iterator_traits<InputIterator>::difference_type count_if (InputIterator first, InputIterator last, UnaryPredicate pred) { typename iterator_traits<InputIterator>::difference_type ret = 0; while (first!=last) { if (pred(*first)) ++ret; ++first; } return ret; }
参数:
first,last:
输入迭代器指向序列的初始位置和末尾位置。这使用的范围[first,last)包括了first到last的所有元素,包括first迭代器
指向的元素,但是不包括last迭代器指向的元素。
pred:
一元函数接受范围内的一个元素作为参数,并返回一个可以转换为bool的值。这返回值意味着这元素是否被函数计算
在内。该函数不应该修改它的参数。这个参数可以是一个函数指针或者函数对象。
返回值:
在范围[first,last)中使pred返回true的元素个数。这返回值的类型为有符号的int型。
例子:
// count_if example #include <iostream> // std::cout #include <algorithm> // std::count_if #include <vector> // std::vector bool IsOdd (int i) { return ((i%2)==1); } int main () { std::vector<int> myvector; for (int i=1; i<10; i++) myvector.push_back(i); // myvector: 1 2 3 4 5 6 7 8 9 int mycount = count_if (myvector.begin(), myvector.end(), IsOdd); std::cout << "myvector contains " << mycount << " odd values.\n"; return 0; }
输出:
myvector contains 5 odd values.
时间复杂度:
O(n)
内容总结
以上是互联网集市为您收集整理的c++ algorithm之count_if全部内容,希望文章能够帮你解决c++ algorithm之count_if所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。