代码改变世界

homework-09

2013-11-25 14:03  adun_li  阅读(130)  评论(0编辑  收藏  举报

  这次作业主要考察C++11的简单用法,个人感觉这样的练习对我这种编程能力比较差的非常有用,加深了对C++11的理解。

 

Lambda的用法

  计算“Hello World!”中

  a.字母‘e’的个数

  b. 字母‘l’的个数
 
代码如下:
 
 1 #include<iostream>
 2 #include<cstring>
 3 #include<string>
 4 #include<memory>
 5 #include<algorithm>
 6 
 7 using namespace std;
 8 
 9 int main()
10 {
11     string s = "Hello World!";
12     int a = 0,b = 0;
13     for_each(s.begin(),s.end(),[&a,&b](char c){
14         if (c == 'l') a++;
15         else if (c == 'e') b++;
16     });
17     cout<<"The number of l is "<< a <<endl;
18     cout<<"The number of e is "<< b <<endl;
19     return 0;
20 }

 

练习使用智能指针

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

 

代码如下:

 1 #include<iostream>
 2 #include<cstring>
 3 #include<string>
 4 #include<memory>
 5 
 6 using namespace std;
 7 
 8 void main(){
 9     int n,i = 0,j;
10     string s = "Hello World!";
11     cin >> n;
12     auto sp1 = std::make_shared<string>(s);
13     auto sp2 = std::make_shared<string>(s);
14     while (i < 12)
15     {
16         j = (i + n) % 12;
17         (*sp2)[j] = (*sp1)[i++];
18     }
19     sp1.reset();
20     cout << *sp2;
21     system("pause");
22     return 0;
23 
24 }