C++ 11 summary video by Embarcadero Japan

Watched C++11 1/2 and C++11 2/2, and tried some of them. It was quick & nice summary.

void Hoge::LambdaTest()
{
    int v1=42;
    auto f1 = [v1] { return v1; };  // capture value
    auto f2 = [&v1] { return v1; }; // capture reference
    auto f3 = [=] { return v1; };   // capture all values
    
    v1 = 99;
    auto f1result = f1();
    auto f2result = f2();
    
    cout << "f1: " << f1result << endl;
    cout << "f2: " << f2result << endl;
    cout << "f3: " << f3() << endl;
}

void Hoge::PointerTest(){
    auto sp1 = make_shared<int>(42);    //shared_ptr<int> sp1(new int(42));
    auto sp2 = sp1;

    if (sp1) { cout << "sp1: " << *sp1 << endl; }
    if (sp2) { cout << "sp2: " << *sp2 << endl; }
    
    unique_ptr<string> up1(new string("hoge"));
    // unique_ptr<string> up2 = up1;
    unique_ptr<string> up2(up1.release());
    
    if (up1) { cout << "up1: " << *up1 << endl; } // up1 alread released
    if (up2) { cout << "up2: " << *up2 << endl; }
}


void Hoge::InitTest(){
    //int *p1 = new int[10];      // new only
    //int *p2 = new int[10]();    // new + clear
    
    const int elements = 10;
    string* p3 = new string[elements]{"ab", "cd", "ef"};
    int* p4 = new int[elements]{1,2};
    
    cout << "string:" << endl;
    for (int i=0; i<elements; i++){
        cout << i << "[string] :" << p3[i] << endl;
        cout << i << "[int] :" << p4[i] << endl;
            }
}

void Hoge::FuncTest(){
    function<int(int, int)> f = [](int i, int j){ return i*j;};
    cout << f(1,2) << endl;
    cout << f(3,4) << endl;
}

void Hoge::TupleTest(){
    tuple<string, double> book1("B1 123-456", 42.0);    // constructor
    tuple<string, double> book2{"B2 123-456", 42.1};    // initializer
    auto book3 = make_tuple("B3 123-456", 42.2);        // returns <const char*, double>
    auto book4 = make_tuple(string("B4 123-456"), 42.3);// returns <string, double>
    
    cout << "book1: " << get<0>(book1) << ", " << get<1>(book1) << endl;
    cout << "book2: " << get<0>(book2) << ", " << get<1>(book2) << endl;
    cout << "book3: " << get<0>(book3) << ", " << get<1>(book3) << endl;
    cout << "book4: " << get<0>(book4) << ", " << get<1>(book4) << endl;
}

void Hoge::RandomTest(){
    // unsigned int
    default_random_engine e1((unsigned int)time(0));  // unsigned int
    for(int i=0; i<10; i++) {
        cout << "e1:" << e1() << endl;
    }
    
    uniform_int_distribution<unsigned long> u(0, 9);
    for(int i=0; i<10; i++) {
        cout << "u(e1):" << u(e1) << endl;
    }
    
    // 64bit
    mt19937_64 e2(time(0));  // unsigned long long (64bit)
    for(int i=0; i<10; i++) {
        cout << "e2:" << e2() << endl;
    }
}

Leave a Reply

Your email address will not be published. Required fields are marked *