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

简介: 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;
    };
}
相关文章
|
13小时前
|
前端开发 开发者
CSS列表属性:list-style系列属性详解
CSS列表属性:list-style系列属性详解
100 39
|
17小时前
|
存储 编译器 C++
【C++】类和对象④(再谈构造函数:初始化列表,隐式类型转换,缺省值
C++中的隐式类型转换在变量赋值和函数调用中常见,如`double`转`int`。取引用时,须用`const`以防修改临时变量,如`const int& b = a;`。类可以有隐式单参构造,使`A aa2 = 1;`合法,但`explicit`关键字可阻止这种转换。C++11起,成员变量可设默认值,如`int _b1 = 1;`。博客探讨构造函数、初始化列表及编译器优化,关注更多C++特性。
|
1天前
|
JavaScript
DOM 节点列表长度(Node List Length)
`length`属性用于获取DOM节点列表的元素数量。在示例中,代码加载&quot;books.xml&quot;,然后通过`getElementsByTagName(&quot;title&quot;)`获取所有标题节点。使用`for`循环遍历这些节点,输出每个标题的文本内容。
|
1天前
|
存储 Dart
Dart中的集合类型:List(数组/列表)
Dart中的集合类型:List(数组/列表)
6 0
|
2天前
|
C++ 容器
【c++】优先级队列|反向迭代器(vector|list)
【c++】优先级队列|反向迭代器(vector|list)
5 0
|
2天前
|
C++
【c++】list模拟实现(2)
【c++】list模拟实现(2)
9 0
|
2天前
|
C++
【c++】list模拟实现(1)
【c++】list模拟实现(1)
9 0
|
3天前
|
存储 C++ 容器
C++之list容器
C++之list容器
6 0
|
3天前
|
存储 编译器 C语言
【C++航海王:追寻罗杰的编程之路】类与对象你学会了吗?(上)
【C++航海王:追寻罗杰的编程之路】类与对象你学会了吗?(上)
9 2
|
3天前
|
C++
C++职工管理系统(类继承、文件、指针操作、中文乱码解决)
C++职工管理系统(类继承、文件、指针操作、中文乱码解决)
4 0
C++职工管理系统(类继承、文件、指针操作、中文乱码解决)