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;
    }
  • 相关阅读:
    [Bzoj3262]陌上花开(CDQ分治&&树状数组||树套树)
    [洛谷P1501][国家集训队]Tree II(LCT)
    [bzoj2002][Hnoi2010]Bounce 弹飞绵羊(LCT)
    Codeforces Round #683 (Div. 2, by Meet IT) E
    Codeforces Round #683 (Div. 2, by Meet IT) C
    set使用
    Educational Codeforces Round 98 (Rated for Div. 2) D
    Educational Codeforces Round 98 (Rated for Div. 2) B
    arc102a
    树状数组知识点整理二(待)
  • 原文地址:https://www.cnblogs.com/Lmeng/p/3455007.html
Copyright © 2011-2022 走看看