算法之旅,直奔<algorithm>之十 count_if
2013-12-16 12:12
381 查看
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.\n"; system("pause"); return 0; }
相关文章推荐
- 算法之旅,直奔<algorithm>之十 count_if
- 算法之旅,直奔<algorithm>之九 count
- 算法之旅,直奔<algorithm>之七 copy_if
- 算法之旅,直奔<algorithm>之十四 fill_n
- 算法之旅,直奔<algorithm>之二十一 max
- 算法之旅,直奔<algorithm>之三 any_of
- 算法之旅,直奔<algorithm>之十七 find_first_of
- 算法之旅,直奔<algorithm>之二十二 sort
- 算法之旅,直奔<bitset>之五 count
- 算法之旅,直奔<algorithm>之四 binary_search
- 算法之旅,直奔<algorithm>之十二 equal_range
- 算法之旅,直奔<algorithm>之十六 find_end
- 算法之旅,直奔<algorithm>之十八 for_each
- 算法之旅,直奔<algorithm>之十九 includes
- 算法之旅,直奔<algorithm>之六 copy_backward
- 算法之旅,直奔<algorithm>之五 copy
- 算法之旅,直奔<algorithm>之八 copy_n
- 算法之旅,直奔<algorithm>之十三 fill
- 算法之旅,直奔<algorithm>之十一 equal
- 算法之旅,直奔<algorithm>之十五 find