C++ 0X 新特性实例(比较常用的) (转)

本文通过示例介绍了C++标准库中的多种特性,包括使用array进行排序和遍历,利用regex进行字符串匹配和搜索,创建并管理多线程,使用future实现异步操作,定义enum class进行类型安全枚举,利用auto简化变量声明,以及lambda表达式的灵活应用。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

转自:http://www.cnblogs.com/mrblue/p/3141456.html

//array
#include <array>
void Foo1()
{
    array<int, 10> a;
    generate(a.begin(), a.end(), rand);
    sort(a.begin(), a.end());

    for (auto n:a)
    {
        cout<<n<<" ";
    }
    cout<<"sizeof(a) = "<<sizeof(a)<<endl;
}

 

//regex
#include <regex>
void Foo2()
{
    if( regex_match("Hello World!", regex("Hello World!")) )
    {
        cout<<"Math!"<<endl;
    }

    if (regex_search("321Hello World!765", std::regex("Hello")) )
    {
        cout<<"Search!"<<endl;
    }
}

 

//thread
#include <thread>
void Foo3()
{
    thread t1([]
    {
        for (int i = 0; i < 10; i++)
        {
            cout<<"t1:"<<i<<endl;
        }
    }
    );

    thread t2([]
    {
        for (int i = 0; i < 10; i++)
        {
            cout<<"t2:"<<i<<endl;
        }
    }
    );

    t1.join();
    t2.join();
}

 

//future  (暂时没理解)
#include <future>
int Test(int a, int b)
{
    cout<<"Test("<<a<<","<<b<<")"<<endl;
    return a+b;
}
void Foo4()
{
    future<int> f1 = async(Test,1,1);
    cout<<"f1"<<endl;

    future<int> f2 = async(Test,2,2);
    cout<<"f2"<<endl;

    future<int> f3 = async(Test,3,3);
    cout<<"f3"<<endl;

    cout<<f1.get()<<endl<<f2.get()<<endl<<f3.get()<<endl;
}

 

//enum class
void Foo5()
{
#define MAKE_STR(s) #s    
    enum class Type
    {
        I = 0,
        II,
        III,
        IV,
        V
    };

    if( 4==(int)Type::V )
        cout<<MAKE_STR(Type::V)<<endl;
}

 

//auto
#include <vector>
void Foo6()
{
    auto a = 10;
    cout<<a<<endl;

    auto b = 20.0f;
    cout<<b<<endl;

    auto& c = a;
    c++;
    cout<<a<<endl;

    vector<int> vec;
    
    for(int i = 0; i<10; i++)
    {
        vec.push_back(i);
    }

    for(auto i = vec.cbegin(); i!=vec.cend(); i++)
    {
        cout<<*i<<endl;
    }

    auto pF = [&c](int i)->int{ return c+=i; };
    cout<<pF(1)<<endl;
    cout<<a<<endl;
}

 

//lambda
#include <functional>
void Foo7()
{
    int a = 0;
    int b = 10;
    function<int(int)> pA = [&a,b](int i)->int{ return a+=b+i; };
    cout<<pA(a)<<endl;
    cout<<a<<endl;

    //function<int(int)> pB = [&a,b](int i)->int{ return b+=a+i; }; 
    //compile error : 'b': a by-value capture cannot be modified in a non-mutable lambda
    cout<<b<<endl;

    auto pC = [&](int i)->int{ return pA(i); };
    cout<<pC(1)<<endl;
}

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

转载于:https://www.cnblogs.com/MrGreen/p/3279609.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值