count_if(vs2010)
- 引言
这是我学习总结<algorithm>的第十篇,这个重要的地方是设置条件。用的还是蛮多的。(今天下午挺恶心的,一下午就做一个面试题,调代码调傻了。。。痛)
- 作用
count_if 的作用是计算容器中符合条件的元素的个数。
- 原理
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; }
- 实验
在数据集合 { 1 2 3 4 5 6 7 8 9}找出奇数的个数
- 代码
test.cpp
#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. "; system("pause"); return 0; }