问题
- 标准库定义了一个名为count_if的算法,类似find_if,此函数接受一对迭代器,
表示一个输入范围,还接受一个谓词,会对输入范围中每个元素执行。
count_if返回一个计数值,表示谓词有多少次为真。
使用count_if重写我们程序中统计有多少单词长度超过6. - 编写一个lambda,捕获一个局部int变量,并递减变量值,直至它为0,一旦变量为0.
再调用lambda应该不再递减.lambda应该返回一个bool值,值出捕获的变量值
是否为0.
源代码
1:
/*************************************************************************
> File Name: test.10.20.cpp
> Author: puruidong
> Mail: 1@w1520.com
> Created Time: 2014年06月15日
************************************************************************/
#include
#include
#include
using namespace std;
/*****************************
标准库定义了一个名为count_if的算法,类似find_if,此函数接受一对迭代器,
表示一个输入范围,还接受一个谓词,会对输入范围中每个元素执行。
count_if返回一个计数值,表示谓词有多少次为真。
使用count_if重写我们程序中统计有多少单词长度超过6.
***************************************/
void elis(vector
{
sort(vec.begin(),vec.end());
auto count = count_if(vec.begin(),vec.end(),[&](const string &s){return s.size()>=sz;});//sz隐式捕获引用方式..
cout << "元素长度大于等于" << sz << "个长度的元素有:" << count << "个" << endl;
} int main()
{
cout << "输入大于等于6长度的字符:" << endl;
vector
string pa;
while(cin >> pa)
{
vec.push_back(pa);
}
elis(vec,6);
return 0;
}
2:
/*************************************************************************
> File Name: test.10.20.cpp
> Author: puruidong
> Mail: 1@w1520.com
> Created Time: 2014年06月15日
************************************************************************/
#include
#include
#include
using namespace std;
/*****************************
标准库定义了一个名为count_if的算法,类似find_if,此函数接受一对迭代器,
表示一个输入范围,还接受一个谓词,会对输入范围中每个元素执行。
count_if返回一个计数值,表示谓词有多少次为真。
使用count_if重写我们程序中统计有多少单词长度超过6.
***************************************/
void elis(vector
{
sort(vec.begin(),vec.end());
auto count = count_if(vec.begin(),vec.end(),[&](const string &s){return s.size()>=sz;});//sz隐式捕获引用方式..
cout << "元素长度大于等于" << sz << "个长度的元素有:" << count << "个" << endl;
} int main()
{
cout << "输入大于等于6长度的字符:" << endl;
vector
string pa;
while(cin >> pa)
{
vec.push_back(pa);
}
elis(vec,6);
return 0;
}
[puruidong@localhost 10.3.3]$ cat test.10.21.cpp
/*************************************************************************
> File Name: test.10.21.cpp
> Author: puruidong
> Mail: 1@w1520.com
> Created Time: 2014年06月15日
************************************************************************/
#include
#include
#include
using namespace std;
/**************************************************
编写一个lambda,捕获一个局部int变量,并递减变量值,直至它为0,一旦变量为0.
再调用lambda应该不再递减.lambda应该返回一个bool值,值出捕获的变量值
是否为0.
************************************************************/
void elis()
{
int ve = 50 ;
unsigned leng = ve-1;
auto f=[&ve]() -> bool { ve--; if(ve==0){ return true;} return false; };
/* auto s = f();
cout << "test:" << s << endl;*/
for(unsigned i=0;i<=leng;++i)
{
auto fbool = f();
cout << "当前值是:" << ve << "," << ((fbool==1)?"该值为0!":"该值不为0!!") << endl;
}
// return f();
} int main()
{
elis();
return 0;
}