算法之旅,直奔<algorithm>之十 count_if
来源:互联网 发布:apache tomcat下载 编辑:程序博客网 时间:2024/05/22 13:37
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::vectorbool 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 9int mycount = count_if (myvector.begin(), myvector.end(), IsOdd);std::cout << "myvector contains " << mycount << " odd values.\n";system("pause");return 0;}
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;}
#include <iostream> // std::cout#include <algorithm> // std::count_if#include <vector> // std::vectorbool 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 9int mycount = count_if (myvector.begin(), myvector.end(), IsOdd);std::cout << "myvector contains " << mycount << " odd values.\n";system("pause");return 0;}
0 0
- 算法之旅,直奔<algorithm>之十 count_if
- 算法之旅,直奔<algorithm>之二十 make_heap
- 算法之旅,直奔<algorithm>之一 all_of
- 算法之旅,直奔<algorithm>之二 adjacent_find
- 算法之旅,直奔<algorithm>之三 any_of
- 算法之旅,直奔<algorithm>之四 binary_search
- 算法之旅,直奔<algorithm>之五 copy
- 算法之旅,直奔<algorithm>之六 copy_backward
- 算法之旅,直奔<algorithm>之七 copy_if
- 算法之旅,直奔<algorithm>之八 copy_n
- 算法之旅,直奔<algorithm>之九 count
- 算法之旅,直奔<algorithm>之十一 equal
- 算法之旅,直奔<algorithm>之十二 equal_range
- 算法之旅,直奔<algorithm>之十三 fill
- 算法之旅,直奔<algorithm>之十四 fill_n
- 算法之旅,直奔<algorithm>之十五 find
- 算法之旅,直奔<algorithm>之十六 find_end
- 算法之旅,直奔<algorithm>之十七 find_first_of
- vc6.0 最后一个SDK 在windows 7 64位下安装方法
- 努力成为优秀的工程师(华为诺亚方舟实验室首席科学家李航)
- apache mina 基础类研究(一)
- Smali--Dalvik虚拟机指令语言
- Windows Azure 安全最佳实践 - 第 2 部分:Azure 提供哪些现成可用的安全机制
- 算法之旅,直奔<algorithm>之十 count_if
- Java使用Base64
- NYOJ 100 1的个数
- (Relax njuptoj)1009 数的计算(DP)
- Chapter 4. MATLAB语法基础
- Cocos2d-x的2.1.4版本新建项目
- 双数组trie
- 杂记 待整理
- 转载一篇文章 写的很好 关于北京地铁涨价的