您的位置:首页 > 编程语言 > Go语言

算法之旅,直奔<algorithm>之十 count_if

2013-12-15 23:28 330 查看

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 vs2010