C++11部分特性

目录

{}初始化

std::initializer_list

 声明

auto

decltype

nullptr

范围for循环

可变参数模板  

lambda表达式

包装器

function包装器

bind


{}初始化

        在C++98 中,标准 允许使用花括号{}对数组或者结构体元素进行统一的列表初始值设定 。比如:
struct Point
{
 int _x;
 int _y;
};
int main()
{
 int array1[] = { 1, 2, 3, 4, 5 };
 int array2[5] = { 0 };
 Point p = { 1, 2 };
 return 0;
}
C++11 扩大了用大括号括起的列表 ( 初始化列表 ) 的使用范围,使其可用于所有的内置类型和用户自
定义的类型,  使用初始化列表时,可添加等号(=),也可不添加  。
struct Point
{
 int _x;
 int _y;
};
int main()
{
 int x1 = 1;
 int x2{ 2 };
 int array1[]{ 1, 2, 3, 4, 5 };
 int array2[5]{ 0 };
 Point p{ 1, 2 };
 // C++11中列表初始化也可以适用于new表达式中
 int* pa = new int[4]{ 0 };
 return 0;
}
创建对象时也可以使用列表初始化方式调用构造函数初始化
class Date
{
public:
 Date(int year, int month, int day)
 :_year(year)
 ,_month(month)
 ,_day(day)
 {
 cout << "Date(int year, int month, int day)" << endl;
 }
private:
 int _year;
 int _month;
 int _day;
};
int main()
{
 Date d1(2022, 1, 1); // old style
 // C++11支持的列表初始化,这里会调用构造函数初始化
 Date d2{ 2022, 1, 2 };
 Date d3 = { 2022, 1, 3 };
 return 0;
}

std::initializer_list

std::initializer_list的 类型:
int main()
{
 // the type of il is an initializer_list 
 auto il = { 10, 20, 30 };
 cout << typeid(il).name() << endl;
 return 0;
}

在C++中,std::initializer_list主要用于以下几种场景,1.初始化容器,2.初始化自定义类型.3作为函数参数。

 声明

auto

C++98 auto 是一个存储类型的说明符,表明变量是局部自动存储类型, 但是局部域中定义局
部的变量默认就是自动存储类型,所以auto就没什么价值了 C++11 中废弃 auto 原来的用法,将
其用于实现自动类型腿断。这样要求必须进行显示初始化,让编译器将定义对象的类型设置为初
始化值的类型。
int main()
{
int i = 10;
auto p = &i;
auto pf = strcpy;
cout << typeid(p).name() << endl;
cout << typeid(pf).name() << endl;
map<string, string> dict = { {"sort", "排序"}, {"insert", "插入"} };
//map<string, string>::iterator it = dict.begin();
auto it = dict.begin();
return 0;
}

decltype

关键字 decltype 将变量的类型声明为表达式指定的类型。
// decltype的一些使用使用场景
template<class T1, class T2>
void F(T1 t1, T2 t2)
{
decltype(t1 * t2) ret;
cout << typeid(ret).name() << endl;
}
int main()
{
const int x = 1;
double y = 2.2;
decltype(x * y) ret; // ret的类型是double
decltype(&x) p;      // p的类型是int*
cout << typeid(ret).name() << endl;
cout << typeid(p).name() << endl;
F(1, 'a');
return 0;
}

nullptr

由于 C++ NULL 被定义成字面量 0 ,这样就可能回带来一些问题,因为 0 既能指针常量,又能表示
整形常量。所以出于清晰和安全的角度考虑 ,C++11中新增了nullptr,用于表示空指针
#ifndef NULL
#ifdef __cplusplus
#define NULL   0
#else
#define NULL   ((void *)0)
#endif
#endif

范围for循环

C++11引入了一种新的循环结构,称为基于范围的for循环12345。基于范围的for循环可以遍历支持迭代器的集合,如std::vector、std::list等,也可以遍历支持下标操作的集合,如std::array和普通数组12345。

基于范围的for循环的语法如下

for (declaration : range)
    statement

其中,declaration是用于访问序列中元素的变量,range是要遍历的序列,statement是每次迭代要执行的语句
例如,下面的代码将打印出一个std::vector的所有元素

std::vector<int> vec = {1, 2, 3, 4, 5};
for (int i : vec) {
    std::cout << i << std::endl;
}

在这个例子中,i是用于访问vec中元素的变量,vec是要遍历的序列,std::cout << i << std::endl;是每次迭代要执行的语句。

可变参数模板  

 

// Args是一个模板参数包,args是一个函数形参参数包
// 声明一个参数包Args...args,这个参数包中可以包含0到任意个模板参数。
template <class ...Args>
void ShowList(Args... args)
{}
上面的参数 args 前面有省略号,所以 它就是一个可变模版参数,我们把带省略号的参数称为“参数
包”,它里面包含了0到N(N>=0)个模版参数 我们无法直接获取参数包args中的每个参数的,
只能通过展开参数包的方式来获取参数包中的每个参数 ,这是使用可变模版参数的一个主要特
点,也是最大的难点,即如何展开可变模版参数。由于语法不支持使用 args[i] 这样方式获取可变
参数,所以我们的用一些奇招来一一获取参数包的值。
递归函数方式展开参数包
// 递归终止函数
template <class T>
void ShowList(const T& t)
{
 cout << t << endl;
}
// 展开函数
template <class T, class ...Args>
void ShowList(T value, Args... args)
{
 cout << value <<" ";
 ShowList(args...);
}
int main()
{
 ShowList(1);
 ShowList(1, 'A');
 ShowList(1, 'A', std::string("sort"));
 return 0;
}
逗号表达式展开参数包
这种展开参数包的方式,不需要通过递归终止函数,是直接 在expand函数体中展开的 , printarg
不是一个递归终止函数,只是一个处理参数包中每一个参数的函数。这种就地展开参数包的方式
实现的关键是逗号表达式。我们知道逗号表达式会按顺序执行逗号前面的表达式。
expand 函数中的逗号表达式: (printarg(args), 0) 也是按照这个执行顺序,先执行printarg(args),再得到逗号表达式的结果 0 。同时还用到了 C++11 的另外一个特性 —— 初始化列
表,通过初始化列表来初始化一个变长数组 , { (printarg(args), 0)...}将会展开成((printarg(arg1),0),
(printarg(arg2),0), (printarg(arg3),0), etc... ),最终会创建一个元素值都为0的数组int arr[sizeof...
(Args)]。由于是逗号表达式 在创建数组的过程中会先执行逗号表达式前面的部分 printarg(args)
打印出参数,也就是说在构造 int 数组的过程中就将参数包展开了,这个数组的目的纯粹是为了在
数组构造的过程展开参数包
template <class T>
void PrintArg(T t)
{
 cout << t << " ";
}
//展开函数
template <class ...Args>
void ShowList(Args... args)
{
 int arr[] = { (PrintArg(args), 0)... };
 cout << endl;
}
int main()
{
 ShowList(1);
 ShowList(1, 'A');
 ShowList(1, 'A', std::string("sort"));
 return 0;
}

lambda表达式

 C++98中,如果想要对一个数据集合中的元素进行排序,可以使用std::sort方法

#include <algorithm>
#include <functional>
int main()
{
int array[] = {4,1,8,5,3,7,0,9,2,6};
// 默认按照小于比较,排出来结果是升序
std::sort(array, array+sizeof(array)/sizeof(array[0]));
// 如果需要降序,需要改变元素的比较规则
std::sort(array, array + sizeof(array) / sizeof(array[0]), greater<int>());
return 0;
}

如果待排序元素为自定义类型,需要用户定义排序时的比较规则:

struct Goods
{
 string _name;  // 名字
 double _price; // 价格
 int _evaluate; // 评价
 Goods(const char* str, double price, int evaluate)
 :_name(str)
 , _price(price)
 , _evaluate(evaluate)
 {}
};
struct ComparePriceLess
{
 bool operator()(const Goods& gl, const Goods& gr)
 {
 return gl._price < gr._price;
}
};
struct ComparePriceGreater
{
 bool operator()(const Goods& gl, const Goods& gr)
 {
 return gl._price > gr._price;
 }
};
int main()
{
 vector<Goods> v = { { "苹果", 2.1, 5 }, { "香蕉", 3, 4 }, { "橙子", 2.2, 
3 }, { "菠萝", 1.5, 4 } };
 sort(v.begin(), v.end(), ComparePriceLess());
sort(v.begin(), v.end(), ComparePriceGreater());
}
随着 C++ 语法的发展, 人们开始觉得上面的写法太复杂了,每次为了实现一个algorithm算法,
都要重新去写一个类,如果每次比较的逻辑不一样,还要去实现多个类,特别是相同类的命名,
这些都给编程者带来了极大的不便 。因此,在 C++11 语法中出现了 Lambda 表达式。

 

int main()
{
 vector<Goods> v = { { "苹果", 2.1, 5 }, { "香蕉", 3, 4 }, { "橙子", 2.2, 
3 }, { "菠萝", 1.5, 4 } };
 sort(v.begin(), v.end(), [](const Goods& g1, const Goods& g2){
 return g1._price < g2._price; });
 sort(v.begin(), v.end(), [](const Goods& g1, const Goods& g2){
 return g1._price > g2._price; });
 sort(v.begin(), v.end(), [](const Goods& g1, const Goods& g2){
 return g1._evaluate < g2._evaluate; });
 sort(v.begin(), v.end(), [](const Goods& g1, const Goods& g2){
 return g1._evaluate > g2._evaluate; });
}

 

lambda表达式书写格式:[capture-list] (parameters) mutable -> return-type { statement
}
lambda表达式各部分说明
         [capture-list] : 捕捉列表该列表总是出现在lambda函数的开始位置编译器根据[]来
        判断接下来的代码是否为lambda函数捕捉列表能够捕捉上下文中的变量供lambda
        函数使用
         (parameters):参数列表。与普通函数的参数列表一致,如果不需要参数传递,则可以
        连同()一起省略
         mutable:默认情况下,lambda函数总是一个const函数,mutable可以取消其常量
        性。使用该修饰符时,参数列表不可省略(即使参数为空)。
        ->returntype:返回值类型。用追踪返回类型形式声明函数的返回值类型,没有返回
        值时此部分可省略。返回值类型明确情况下,也可省略,由编译器对返回类型进行推
        导。
        {statement}:函数体。在该函数体内,除了可以使用其参数外,还可以使用所有捕获
        到的变量。
注意:
在lambda函数定义中,参数列表和返回值类型都是可选部分,而捕捉列表和函数体可以为
空。因此C++11中最简单的lambda函数为:[]{}; 该lambda函数不能做任何事情。
int main()
{
    // 最简单的lambda表达式, 该lambda表达式没有任何意义
   []{}; 
    
    // 省略参数列表和返回值类型,返回值类型由编译器推导为int
    int a = 3, b = 4;
   [=]{return a + 3; }; 
    
    // 省略了返回值类型,无返回值类型
    auto fun1 = [&](int c){b = a + c; }; 
    fun1(10)
    cout<<a<<" "<<b<<endl;
    
    // 各部分都很完善的lambda函数
    auto fun2 = [=, &b](int c)->int{return b += a+ c; }; 
    cout<<fun2(10)<<endl;
    
    // 复制捕捉x
    int x = 10;
    auto add_x = [x](int a) mutable { x *= 2; return a + x; }; 
    cout << add_x(10) << endl; 
    return 0;
}

 

通过上述例子可以看出, lambda 表达式实际上可以理解为无名函数,该函数无法直接调
用,如果想要直接调用,可借助 auto 将其赋值给一个变量。
捕捉列表描述了上下文中那些数据可以被lambda使用,以及使用的方式传值还是传引用
[var]:表示值传递方式捕捉变量var
[=]:表示值传递方式捕获所有父作用域中的变量(包括this)
[&var]:表示引用传递捕捉变量var
[&]:表示引用传递捕捉所有父作用域中的变量(包括this)
[this]:表示值传递方式捕捉当前的this指针
注意:
a. 父作用域指包含lambda函数的语句块
b. 语法上捕捉列表可由多个捕捉项组成,并以逗号分割。
比如:[=, &a, &b]:以引用传递的方式捕捉变量a和b,值传递方式捕捉其他所有变量
[&,a, this]:值传递方式捕捉变量a和this,引用方式捕捉其他变量
c. 捕捉列表不允许变量重复传递,否则就会导致编译错误。

比如:[=, a]:=已经以值传递方式捕捉了所有变量,捕捉a重复

d. 在块作用域以外的lambda函数捕捉列表必须为空。
e. 在块作用域中的lambda函数仅能捕捉父作用域中局部变量,捕捉任何非此作用域或者
非局部变量都会导致编译报错。
f. lambda表达式之间不能相互赋值,即使看起来类型相同
void (*PF)();
int main()
{
 auto f1 = []{cout << "hello world" << endl; };
 auto f2 = []{cout << "hello world" << endl; };
    // 此处先不解释原因,等lambda表达式底层实现原理看完后,大家就清楚了
 //f1 = f2;   // 编译失败--->提示找不到operator=()
    // 允许使用一个lambda表达式拷贝构造一个新的副本
 auto f3(f2);
 f3();
 // 可以将lambda表达式赋值给相同类型的函数指针
 PF = f2;
 PF();
 return 0;
}

 

函数对象,又称为仿函数,即可以想函数一样使用的对象,就是在类中 重载了operator()运算符
类对象。
class Rate
{
public:
 Rate(double rate): _rate(rate)
 {}
 double operator()(double money, int year)
 { return money * _rate * year;}
private:
 double _rate;
};
int main()
{
// 函数对象
 double rate = 0.49;
 Rate r1(rate);
 r1(10000, 2);
// lamber
 auto r2 = [=](double monty, int year)->double{return monty*rate*year; 
};
 r2(10000, 2);
 return 0;
从使用方式上来看,函数对象与 lambda 表达式完全一样。
函数对象将 rate 作为其成员变量,在定义对象时给出初始值即可, lambda 表达式通过捕获列表可
以直接将该变量捕获到。

 

实际在底层编译器对于 lambda 表达式的处理方式,完全就是按照函数对象的方式处理的,即 :如
果定义了一个lambda表达式,编译器会自动生成一个类,在该类中重载了operator()。

包装器

 

function包装器

function 包装器 也叫作适配器。 C++ 中的 function 本质是一个类模板,也是一个包装器。
template<class F, class T>
T useF(F f, T x)
{
 static int count = 0;
 cout << "count:" << ++count << endl;
 cout << "count:" << &count << endl;
 return f(x);
}
double f(double i)
{
 return i / 2;
}
struct Functor
{
 double operator()(double d)
 {
 return d / 3;
 }
};
int main()
{
// 函数名
 cout << useF(f, 11.11) << endl;
 // 函数对象
 cout << useF(Functor(), 11.11) << endl;
 // lamber表达式
 cout << useF([](double d)->double{ return d/4; }, 11.11) << endl;
 return 0;
}
通过上面的程序验证,我们会发现useF函数模板实例化了三份
包装器可以很好的解决上面的问题

 

// 使用方法如下:
#include <functional>
int f(int a, int b)
{
 return a + b;
}
struct Functor
{
public:
 int operator() (int a, int b)
 {
 return a + b;
 }
};
class Plus
{
public:
 static int plusi(int a, int b)
 {
 return a + b;
 }
 double plusd(double a, double b)
 {
 return a + b;
 }
};
int main()
{
 // 函数名(函数指针)
 std::function<int(int, int)> func1 = f;
 cout << func1(1, 2) << endl;
 // 函数对象
 std::function<int(int, int)> func2 = Functor();
 cout << func2(1, 2) << endl;
 // lamber表达式
 std::function<int(int, int)> func3 = [](const int a, const int b) 
{return a + b; };
 cout << func3(1, 2) << endl;
 
 // 类的成员函数
 std::function<int(int, int)> func4 = &Plus::plusi;
 cout << func4(1, 2) << endl;
 std::function<double(Plus, double, double)> func5 = &Plus::plusd;
 cout << func5(Plus(), 1.1, 2.2) << endl;
 return 0;
}

 

#include <functional>
template<class F, class T>
T useF(F f, T x)
{
 static int count = 0;
 cout << "count:" << ++count << endl;
 cout << "count:" << &count << endl;
 return f(x);
}
double f(double i)
{
 return i / 2;
}
struct Functor
{
 double operator()(double d)
 {
 return d / 3;
 }
};
int main()
{// 函数名
 std::function<double(double)> func1 = f;
 cout << useF(func1, 11.11) << endl;
 // 函数对象
 std::function<double(double)> func2 = Functor();
 cout << useF(func2, 11.11) << endl;
 // lamber表达式
 std::function<double(double)> func3 = [](double d)->double{ return d /
4; };
 cout << useF(func3, 11.11) << endl;
 return 0;
}

 

bind

std::bind 函数定义在头文件中, 是一个函数模板,它就像一个函数包装器(适配器)接受一个可
调用对象(callable object),生成一个新的可调用对象来“适应”原对象的参数列表 一般而
言,我们用它可以把一个原本接收 N 个参数的函数 fn ,通过绑定一些参数,返回一个接收 M 个( M
可以大于 N ,但这么做没什么意义)参数的新函数。同时,使用 std::bind 函数还可以实现参数顺
序调整等操作。
// 原型如下:
template <class Fn, class... Args>
/* unspecified */ bind (Fn&& fn, Args&&... args);
// with return type (2) 
template <class Ret, class Fn, class... Args>
/* unspecified */ bind (Fn&& fn, Args&&... args);
可以将 bind 函数看作是一个通用的函数适配器,它接受一个可调用对象,生成一个新的可调用对 象来“ 适应 原对象的参数列表。
调用 bind 的一般形式: auto newCallable = bind(callable,arg_list);
其中, newCallable 本身是一个可调用对象, arg_list 是一个逗号分隔的参数列表,对应给定的 callable的参数。 当我们调用 newCallable 时, newCallable 会调用 callable, 并传给它 arg_list 的参数
arg_list 中的参数可能包含形如 _n 的名字,其中 n 是一个整数,这些参数是 占位符 ,表示
newCallable 的参数,它们占据了传递给 newCallable 的参数的 位置 。数值 n 表示生成的可调用对 象中参数的位置:_1 newCallable 的第一个参数, _2 为第二个参数,以此类推
#include <functional>
int Plus(int a, int b)
{
 return a + b;
}
class Sub
{
public:
 int sub(int a, int b)
 {
 return a - b;
 }
};
int main()
{
 //表示绑定函数plus 参数分别由调用 func1 的第一,二个参数指定
 std::function<int(int, int)> func1 = std::bind(Plus, placeholders::_1, 
placeholders::_2);
 //auto func1 = std::bind(Plus, placeholders::_1, placeholders::_2);
 //func2的类型为 function<void(int, int, int)> 与func1类型一样
 //表示绑定函数 plus 的第一,二为: 1, 2
 auto  func2 = std::bind(Plus, 1, 2);   
 cout << func1(1, 2) << endl;
 cout << func2() << endl;
 Sub s;
 // 绑定成员函数
 std::function<int(int, int)> func3 = std::bind(&Sub::sub, s, 
placeholders::_1, placeholders::_2);
 // 参数调换顺序
std::function<int(int, int)> func4 = std::bind(&Sub::sub, s, 
placeholders::_2, placeholders::_1);
 cout << func3(1, 2) << endl; 
 cout << func4(1, 2) << endl;
 return 0;
}

 

 

  • 19
    点赞
  • 20
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值