C++11中的{}与std::initializer_list

文章目录

1.C++11中的{}

1.1.C++98中传统的{}

用于对一般数组结构体的初始化

cpp 复制代码
struct A {
	int _x;
	int _y;
};
int main() 
{
	int arr1[] = { 1,2,3,4,5,6 };
	int arr2[] = { 0 };
	A a = { 3,4 };

	return 0;
}

1.2.C++11中的{}

  • 从C++11开始,想要统一初始化方式,实现一切对象都可用{}进行初始化,用{}初始化也叫列表初始化
  • 内置类型和自定义类型均支持用{}初始化,自定义类型本质是隐式类型转换,会产生临时变量(优化以后变成直接构造)
  • 用{}初始化,=可以省略
  • C++11中列表初始化统一了初始化方,在用多参数构造对象时,用{}初始化(相比有名对象和匿名对象传参)会方便很多
cpp 复制代码
#include <iostream>
#include <vector>
using namespace std;
struct A {
	int _x;
	int _y;
};
class Student {
public:
	Student(const string& name, const int id = 0, const int age = 0)
		:_name(name)
		,_id(id)
		,_age(age){}
	Student(const Student& s) 
		:_name(s._name)
		,_id(s._id)
		,_age(s._age){ }
private:
	string _name;
	int _id;
	int _age;
};
int main() 
{
	// C++98中的{}
	int arr1[] = { 1,2,3,4,5,6 };
	int arr2[] = { 0 };
	A a = { 3,4 };

	//C++11中的{}
	//内置类型初始化
	int a = { 1 };
	//自定义类型初始化
	Student stu1 = { "WangPeng", 20251117, 19 };
	//这里stu2引用的是{ "YiYi", 20258888, 18 }临时变量
	const Student& stu2 = { "YiYi", 20258888, 18 };
	
	//只有{}初始化,才可以省略=
	double num{ 3.14159 };
	Student s{ "ZhangWei", 20236666, 22 };

	vector<Student> students;
	students.push_back(stu1);
	students.push_back(Student{ "WangPeng", 20251117, 19 });

	//相比有名对象和匿名对象传参,{}更加方便
	students.push_back({ "WangPeng", 20251117, 19 });

	return 0;
}

2.std::initializer_list

  • 通过{}初始化已经很方便了,但是对象容器的初始化还是不太方便,假设想对一个vector对象进行初始化,要用N个值构造初始化,那么需要构造多次才能实现(因为容器中元素数量不确定,所以每个元素都要执行对应的构造函数)
cpp 复制代码
vector<int> = {1, 2, 3, 4};
  • C++11库中,新增了一个std::initializer_list类,它的本质是底层开一个数组,将数据拷贝到数组中,其中包含两个指针分别指向开始(begin)和结束(end)
cpp 复制代码
auto il = {98, 99, 100};
  • initializer_list支持迭代器遍历
  • STL中的容器支持std::initializer_list的构造函数(即支持任意多个值构成的{x1, x2, x3, ...}进行初始化)
cpp 复制代码
#include <iostream>
#include <vector>
#include <map>
using namespace std;
int main()
{
	std::initializer_list<int> mylist;
	mylist = { 23,24,25,26,27 };
	int i = 0;
	//my_list中只存了两个首尾指针(在64位环境下大小均为8个字节)
	cout << sizeof(mylist) << endl;//输出16 
	//首尾指针地址与变量i地址接近 说明该数组存储在栈上
	cout << mylist.begin() << endl;
	cout << mylist.end() << endl;
	cout << &i << endl;

	//直接构造
	vector<int> v1({ 1,2,3,4,5 });
	//构造临时对象->临时对象拷贝给v2->优化为直接构造
	vector<int> v2 = { 6,7,8,9,10 };
	const vector<int>& v3 = { 11,22,33,44,55 };

	//pair类型的{}初始化 + map的initializer_list构造
	map<string, string> dict = { {"a","一个"},{"stack","栈"},{"queue","队列"} };

	//initializer_list赋值可以这样写
	v1 = { 111,222,333,444,555 };

	return 0;
}
相关推荐
小鸡吃米…1 小时前
Python 列表
开发语言·python
kaikaile19951 小时前
基于C#实现一维码和二维码打印程序
开发语言·c#
我不是程序猿儿2 小时前
【C#】画图控件的FormsPlot中的Refresh功能调用消耗时间不一致缘由
开发语言·c#
rit84324992 小时前
C# Socket 聊天室(含文件传输)
服务器·开发语言·c#
kk哥88992 小时前
C++ 对象 核心介绍
java·jvm·c++
helloworddm2 小时前
WinUI3 主线程不要执行耗时操作的原因
c++
嘉琪0012 小时前
Vue3+JS 高级前端面试题
开发语言·前端·javascript
xunyan62342 小时前
面向对象(下)-接口的理解
java·开发语言
遥不可及~~斌3 小时前
Java 面试题集 -- 001
java·开发语言
2501_921649493 小时前
如何获取美股实时行情:Python 量化交易指南
开发语言·后端·python·websocket·金融