zoukankan      html  css  js  c++  java
  • 【现代程序设计】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;
    }
  • 相关阅读:
    Xcode 6 下添加pch头文件
    兵器簿之github的配置和使用
    sql 2005性能调优
    C#遍历枚举(Enum)值
    使用 jQuery 调用 ASP.NET AJAX Page Method
    强制不使用“兼容性视图”的HTML代码
    HR在ERP实施过程中的作用
    WdatePicker日历添加事件,在任意月改变时处理日期事件
    JQuery实现表格自动增加行,对新行添加事件
    获取元素离文档各边的距离
  • 原文地址:https://www.cnblogs.com/Lmeng/p/3455007.html
Copyright © 2011-2022 走看看