【现代程序设计】homework-09

1. 了解Lambda的用法

计算“Hello World!”中

a.字母‘e’的个数

b. 字母‘l’的个数 

 首先:

ISO C++ 11 标准的另一大亮点是引入Lambda表达式。语法如下:
[](形参列表)->返回值类型{函数体}
例如调用<algorithm>中的std::sort,ISO C++ 98 的写法是要先写一个compare函数:
1
2
3
4
bool compare(int & a, int & b)
{
    return a > b;   // 降序排序
}
然后,再这样调用:
1
sort(a, a+n, compare);
然而,用ISO C++ 11 标准新增的Lambda表达式,可以这么写:
1
sort( a, a+n, [](int & a, int & b)->bool{return a > b;} ); // 降序排序
这样一来,代码明显简洁多了

针对该题,代码如下:

#include "stdafx.h"
#include <iostream>
#include <string>
#include <memory>
#include<algorithm>
using namespace std;

int main()
{
    string str;
    cin>>str;
    int c1=count_if(str.begin(),str.end(),[](char tmp)->bool{return tmp == 'e';});
    int c2=count_if(str.begin(),str.end(),[](char tmp)->bool{return tmp == 'l';});
    cout<<"e的数量: "<<c1<<"l的数量: "<<c2<<endl;
    return 0;
}

 

2. 练习使用智能指针

  打印“Hello World!”循环右移n位的结果

  Example:

    n = 1, output = “!Hello World”

  n = 3, output = “ld!Hello Wor”

#include "stdafx.h"
#include <iostream>
#include <string>
#include <memory>
using namespace std;
unique_ptr<string  > move ( string str,int n);
int main( )
{
    int n;
    cin>>n;
    string str;
    cin>>str;
    move (str , n);
    return 0;
}
unique_ptr<string  > move ( string str,int n){

    unique_ptr<string>tmp(new string(str));
    int length=str.length();
      for(int i=0;i<n;i++)    
      {
          char ch=(*tmp)[length-1];
          for(int j=length-1;j>0;j--)
          {
              (*tmp)[j]=(*tmp)[j-1];
          }
         (*tmp)[0]=ch;
     }
     cout<<*tmp<<endl;
     return tmp;
}

 

 

 

 

转载于:https://www.cnblogs.com/Lmeng/p/3455007.html

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值