1. 在C++98中,标准允许使用花括号{}来对数组元素进行统一的集合(列表)初始化操作,如:int buf[] = {0};int arr[] = {1,2,3,4,5,6,7,8};
可是对于自定义的类型,却是无法这样去初始化的,比如STL标准模板库中容器,使用的频率非常之高,如vector,若要初始化其内容,则需要每次进行push_back
或使用迭代器去初始化,这是极其不便的。C++11 中,可以”列表初始化“方式来快速的初始化内置类型或STL中容器。
2.集合(列表)的初始化方式已经成为C++语言的一个基本功能,列表初始化的方式对:内置类型(int、float、double、char等)、数组、自定义的类、函数参数列表、STL标准模板库等都是有效的。
/*************************************************************************
* File Name: Init.cpp
* Author: The answer
* Function: Other
* Mail: [email protected]
* Created Time: 2018年09月09日 星期日 22时36分21秒
************************************************************************/
#include <iostream>
#include <string>
#include <vector>
#include <set>
#include <map>
using namespace std;
#define ARR_LEN(array) sizeof(array)/sizeof(array[0])
template<typename T>
void DisplasyStl(T u, int len){
for(auto i = 0;i < len;++i){
std::cout<<u[i]<<" ";
}
std::cout<<std::endl;
}
void DisplayMap(map<int,std::string> _map) {
for(auto c:_map)
{
std::cout<<c.first<<" "<<c.second<<"|";
}
std::cout<<std::endl;
}
int main(int argc,char **argv)
{
int arr[] = {1,2,3,4,5,6,7,8,9,10}; //c++98编译通过 c++11编译通过
DisplasyStl(arr,ARR_LEN(arr));
int buf[]{11,22,33,44,55,66,77}; //c++98编译失败
DisplasyStl(buf,ARR_LEN(buf));
vector<int> _vec= {10,20,30,40,50,60}; //c++98编译失败
for(auto u: _vec){std::cout<<u<<" ";}
std::cout<<std::endl;
//c++98编译失败
map<int,std::string> _map{{1,"lxg"},{2,"the answer"},{3,"hello world."}};
DisplayMap(_map);
return 0;
}
<font color=#0099ff size=4 face="黑体">编译打印结果:
```c++
1 2 3 4 5 6 7 8 9 10
11 22 33 44 55 66 77
10 20 30 40 50 60
1 lxg|2 the answer|3 hello world.|
3. 初始化列表可以在花括号“{}”之前使用等号=,其效果与不带等号的初始化相同。如:int a{10}
和 int a = {10}
。 所以,自动化变量和全局变量的初始化在C++11中被丰富了。比如可以使用以下几种方式来完成初始化操作:
① 等号“=” 加上赋值表达式(assignment_expression)。如:int a = 1+2.
② 等号“=”加上花括号{}的初始化列表。如:int b = {1+3}.
③ 圆括号式的表达式列表。如:int a(1+2).
④ 花括号{}的初始化列表。如:int a{1+3}.
③④两种方式也可以 用new操作符中。比如:int *p = new int(2); char *c = new char{'g'};
4. 正如2.中所描述,列表初始化方式同样也适用于自定义的类中。因为标准模板库中容器对初始化类别的支持源自于 <initializer_list>
头文件中<initializer_list
类模板的支持。因此,只需要在应用中#include <initializer_list>
头文件,同时声明一个以 initializer_list<T>
模板类为参数的构造函数。
代码2.
———-
打印结果:1 3 5 7 9 11
代码3.
打印结果:1 lxg 2 the answer 3 lsh
5. 初始化列表用于函数参数中.
打印结果:10 20 30 40 50 60