【现代程序设计】homework-09

时间:2023-03-08 21:44:25
【现代程序设计】homework-09

1. 了解Lambda的用法

计算“Hello World!”中

a.字母‘e’的个数

b. 字母‘l’的个数

首先:

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

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 ;
}
unique_ptr<string > move ( string str,int n){ unique_ptr<string>tmp(new string(str));
int length=str.length();
for(int i=;i<n;i++)
{
char ch=(*tmp)[length-];
for(int j=length-;j>;j--)
{
(*tmp)[j]=(*tmp)[j-];
}
(*tmp)[]=ch;
}
cout<<*tmp<<endl;
return tmp;
}