C 语言

关注公众号 jb51net

关闭
首页 > 软件编程 > C 语言 > c++  std::initializer_list

C++11中的{}与std::initializer_list深度解析

作者:学困昇

C++11引入了统一的初始化方式,使用{}进行初始化,支持内置类型和自定义类型,C++11还引入了std::initializer_list类,支持对容器的初始化,方便地用多参数构造对象,本文给大家介绍的非常详细,感兴趣的朋友跟随小编一起看看吧

1.C++11中的{}

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

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

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中的{}

#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<int> = {1, 2, 3, 4};
auto il = {98, 99, 100};
#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;
}

到此这篇关于C++11中的{}与std::initializer_list的文章就介绍到这了,更多相关c++ std::initializer_list内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

您可能感兴趣的文章:
阅读全文