C++11 列表初始化(initializer_list),pair

1. {} 初始化

C++98 中,允许使用 {} 对数组进行初始化。

	int arr[3] = {
    
     0, 1, 2 };

C++11 扩大了 {} 初始化 的使用范围,使其可用于所有内置类型和自定义类型。

struct Date
{
    
    
    int _year;
    int _month;
    int _day;
    Date(int year, int month, int day)
        :_year(year)
        ,_month(month)
        ,_day(day)
    {
    
    }
};

int main()
{
    
    
    // 两种常见的用法:
    Date d1{
    
    2024, 6, 8};
    Date d2 = {
    
    2024, 6, 8};

    // 列表初始化可用于 new 表达式
    int* pa = new int[4]{
    
     0 };

    return 0;
}

2. std::initializer_list

int main()
{
     
     
    auto arr = {
     
      1, 2, 3 };
    cout << typeid(arr).name() << endl; // typeid().name() 用于查看对象的数据类型

    return 0;
}

std::initializer_list 是 C++11 引入的一个模板类型,用于处理一组同类型的初始值。

主要用于构造函数和函数参数列表中,允许使用 {} 初始化或传递一系列相同类型的值。

std::initializer_list 作为构造函数的参数,C++11 对不少容器增加了 initializer_list 作为参数的构造函数:

std::initializer_list 作为 operator=() 的函数参数:

常见的使用场景:

int main()
{
    
    
    map<string, string> dict{
    
     {
    
    "iterator", "迭代器"}, {
    
    "singularity", "奇异"}, {
    
    "sort", "排序"} };
    vector<int> v = {
    
     1, 2, 3, 4, 5 };

    return 0;
}

3. pair 的补充知识

namespace MyTest 
{
    
    
	template<class T1, class T2>
    struct pair
    {
    
    
        pair(const T1& first, const T2& second)
            :_first(first)
            ,_second(second)
        {
    
    }

        template<class K, class V>
        pair(const pair<K, V>& kv)
            :_first(kv._first)
            ,_second(kv._second)
        {
    
    }

    
        T1 _first;
        T2 _second;
    };
}

猜你喜欢

转载自blog.csdn.net/taduanlangan/article/details/139545886