stl疑问三:any_of, none_of,all_of解析(c++11 特型的说明)


今天,遇到下面一个问题:

 从容器中判断,是否有一个元素是否满足FN()的,如果满足返回true;

,就想到了这个算法(any_of)。下面,我就把any_of,和相关的几个方法都做一下说明.


方法说明

any_of(开始,结束,条件函数(fn)):

用法:在[ 开始,结束)这个区间, 判断是否有一个元素满足 fn;

示例:

// any_of example
#include <iostream>     // std::cout
#include <algorithm>    // std::any_of
#include <array>        // std::array

int main () {
  std::array<int,7> foo = {0,1,-1,3,-3,5,-5};

  if ( std::any_of(foo.begin(), foo.end(), [](int i){return i<0;}) )
    std::cout << "There are negative elements in the range.\n";

  return 0;
}


none_of(开始,结束,条件函数fn):

用法:在 [开始,结束)这个区间,所有元素都不满足fn,返回true ,否则返回false

示例:

// none_of example
#include <iostream>     // std::cout
#include <algorithm>    // std::none_of
#include <array>        // std::array

int main () {
  std::array<int,8> foo = {1,2,4,8,16,32,64,128};

  if ( std::none_of(foo.begin(), foo.end(), [](int i){return i<0;}) )
    std::cout << "There are no negative elements in the range.\n";

  return 0;
}


all_of(开始,结束,函数fn):

用法:在[开始,结束)这个所有元素都满足fn 则返回ture,否则返回false

示例

// all_of example
#include <iostream>     // std::cout
#include <algorithm>    // std::all_of
#include <array>        // std::array

int main () {
  std::array<int,8> foo = {3,5,7,11,13,17,19,23};

  if ( std::all_of(foo.begin(), foo.end(), [](int i){return i%2;}) )
    std::cout << "All the elements are odd numbers.\n";

  return 0;
}



对于上面的  示例,如果你是用的是c++11以下的编译器,是找不到这几个方法的,及后面条件函数都不认识;所以最好用兼容c++11的编译器,如vs2010及以上版本。

Lambda表达式

看这么久是不是,对 上面条件函数方法很不明白,其实我当时也有一样的困惑,后来我就查了下c++11新特性终于明白了。因为c++11加了个Lambda表达式
特性,说起这个Lambda表达式,如果学过python 应该都明白。

Lambda表达式允许你在本地定义函数,即在调用的地方定义,从而消除函数对象产生的许多安全风险,Lambda表达式的格式如下:

[capture](parameters)->return-type {body} []里是函数调用的参数列表,表示一个Lambda表达式的开始

c++11新特性链接

http://developer.51cto.com/art/201106/270597.htm



  • 3
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值