C++11 新特性练习

来源:互联网 发布:ubuntu创建文件夹16.04 编辑:程序博客网 时间:2024/05/16 02:15

// C++TR1(Technology Report)中包含一个function模板类和bind模板函数,使用它们可以实现类似函数指针的功能


#include <iostream>

#include <vector>

#include <algorithm>


#include <functional>


using namespace std;


void printA(int a)

{

    cout << a << endl;

}


void fun(int a,int b, int c)

{

    cout << a << b << c << endl;

}


int main(int argc,const char * argv[])

{

/*

    vector<int> v = {3,2,1,0};

    

    {

 //     for_each( v.begin(), v.end(), [=](int x){ cout << x + 1<< endl;} );

    }

    

    {

        int a =2, b=1;

        for_each(v.begin(), v.end(), [a](int &x) mutable { cout << x +a << endl ;

            a++;

                  } );

        cout  <<  " a : " << a <<endl;

    }  //   加上mutable  修饰符后,可以修改按值传递进来的拷贝

    


    

    {

        int a =2, b=1;

        for_each(v.begin(), v.end(), [&](int x) {  cout <<x+a ; a++; } ); // =

        cout << "   "  << a << endl;

    }

    

    {

        int a=1;

        for_each(v.begin(), v.end(), [this](int v) {

             cout << v+m_nData << endl

            });

    }  // C++11 语法记录

    

    {

        [](){}

    }

    */

    

    /************************************************

    

     ************************************************/

 /*   std::function<void(int a)> f ;

    f = printA;

    f(2);

    

    //std::function<void ()> f = [](){cout << "***" ; };

    

    std::function<void()>fun1 = [](){cout << "hello world !" << endl ;};

    fun1();

    */

    

    auto f =  std::bind(fun,1, 2, 3); //表示绑定fun函数的 1 2 3

    f();

    

    auto  f1 =std::bind(fun,placeholders::_1,placeholders::_2,60);

    //  f1();绑定f()函数调用的第二个和第三个参数,返回一个新的函数对象为ff,它只带有一个int类型的参数

    f1(1, 2);

    

   // auto f2 = std::bind(fun, placeholders::_3,placeholders::_1,2);

    auto f2 =std::bind(fun,placeholders::_1,2,placeholders::_3);

  //  auto f2 = std::bind(fun, placeholders::_2,placeholders::_1, 3);

    f2(1, 2);

    

    return 0;

}




***************************************************

using namespace std;


struct TEST

{

    int a;

    int b;

    int c;

};


struct  TT

{

    char *name;

    int     id;

};


//括号初始化语法如下:对于POD聚合,你还可以使用大括号:

int main(int argc,const char * argv[])

{


    

  /*  TT  *test = (TT *)malloc(sizeof(TT));

    

    TEST T  = {10,20,30};

    TEST T1 = {

               .a = 10,

   

                c:60

                };

    printf("%d %d  %5d\n", T.a, T.b, T.c);

    printf("%d   %5d\n", T.a, T.c);

   */

    

    

  /*  vector<int>a(10,2);

    

    for(auto &d : a)

    {

        d =d+2;

        cout << d << '\n';

    }

  // C++11使用统一的大括号符号

    vector<string>str = {"d","fds"};

    begin(a);

    

    int *p= new int[3] {1,2,3} ;

    */

    return 0;

}


0 0
原创粉丝点击