zoukankan      html  css  js  c++  java
  • 算法之旅,直奔<algorithm>之十 count_if

    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;
    }


  • 相关阅读:
    FASTJSON
    数据库索引(转)
    设计模式
    jQuery EasyUI教程之datagrid应用(三)
    EasyUI---tree
    EasyUI、Struts2、Hibernate、spring 框架整合
    eclipse最有用快捷键整理
    框架整合----------Hibernate、spring整合
    jQuery EasyUI教程之datagrid应用(二)
    marquee 标签 文字滚动
  • 原文地址:https://www.cnblogs.com/riasky/p/3476484.html
Copyright © 2011-2022 走看看