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;
}
相关推荐
誰能久伴不乏16 分钟前
用 UDP 做一条“可靠“的控制通道
c++·qt·网络协议·udp
十五年专注C++开发33 分钟前
FlatBuffers: 一个高效的零拷贝二进制序列化库
c++·序列化·反序列化·flatbuffers
BuHuaX1 小时前
Lua 与 ToLua:运行机制及热更新原理
开发语言·unity·junit·c#·lua
xys_6781 小时前
深挖C++:C++入门基础
开发语言·c++
高冷小鱼殿下1 小时前
C 语言指针与输入输出
c++
幻境如梦丶皆为虚2 小时前
从零写一个 DSH 插件:在左侧菜单栏加一个「测试」
开发语言·javascript·ecmascript
LabVIEW开发2 小时前
LabVIEW 局部变量与数据流:这道 CLAD 题为什么答案是 Undefined
java·开发语言·labview
路溪非溪2 小时前
C++标准库之智能指针
linux·开发语言·c++
hetao17338372 小时前
2026-11-02 hetao1733837 的刷题记录
c++·算法