C++11auto

1、auto
使用auto必须初始化
auto x = 5;            //x int
const auto *v = &x, u = 6;    //v const int*, u const int

auto限制
void func(auto a = 1)    //error, auto不能用于函数参数
{}

struct sFoo
{
    auto var1 = 0;    //error, auto不能应用于非静态成员变量
    static const auto var2 = 0;
};

template <typename T>
struct  Bar
{

};

int main()
{
    int arr[10] = { 0 };
    auto aa = arr;        //aa-> int *
    auto rr[10] = arr;    //error, auto无法定义数组

    Bar<int>bar;
    Bar<auto> bb = bar;    //error, auto无法推导出模板参数

    return 0;
}
2、decltype 获知表达式的类型

3、for的新用法、function和bind 以及ambda表达式
#include <iostream>
#include<vector>
#include<algorithm>
#include<functional>

using namespace std;

void func(int x)
{
    cout << "bind " << x << endl;
}
int main()
{
    vector<int> vec;
    for (int i = 0; i < 10; i++)
        vec.push_back(i);
    //for遍历新写法

    for (auto &k : vec)//带&会改变原来容器中的值
    {
        cout << k++ << endl;
    }
    cout << "****************" << endl;//输出0~9
    for (auto j : vec)
    {
        cout << j << endl;
    }
    cout << "****************" << endl;//vec中的值被k改变,输出的值为1~10

    //function和bind
    cout << "function and bind" << endl;
    function<void(int)> f = bind(func, placeholders::_1);
    f(100);
    auto f1 = bind(func, placeholders::_1);
    f1(10);
    可用于回调函数了,比如在界面上显示操作层中的某数值
    1、显示层
    //auto FucCallBack = bind(&UI::ShowData, this, placeholders::_1);
    //m_OP->SetCbk(FucCallBack);
    2、操作层
    //std::function<void(int)> m_cbk;
    //void OP::SetCab(std::function<void(int)> cbk)
    //{
    //    m_cbk = cbk;
    //}
    用m_cbk返回需要显示的数值data
    //m_cbk(data);

    cout << "lambda" << endl;
    //lambda表达式
    //[capture] (params) opt -> ret {body;};
    //captrue 捕获列表,比如:
    //    [=, &x, &y]表示外部变量 x、y 的值可以被修改,其余外部变量不能被修改;
    //    [&, x, y]表示除 x、y 以外的外部变量,值都可以被修改。
    //params 参数表
    //opt 函数选项
    //ret 返回值类型
    //body 函数体

    //完整的lambda表达式
    auto f = [](int a)->int {return a; };

    int event = 0;
    for_each(vec.begin(), vec.end(), [&event](int val)
    {
        if ((val % 2) == 0)
        {
            event++;
            cout << val << endl;
        }
    });
    int cont = count_if(vec.begin(), vec.end(), [](int val)
    {
        return val > 8;
    });
    cout << "个数=" << cont << endl;
    cout << "偶数个数="<<event <<endl;
    return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值