C ++中的初始化程序列表– std :: initializer_list

本文介绍了C++中的初始化列表(std::initializer_list),包括其定义、用途和优势。通过示例展示了如何在类构造函数中使用初始化列表进行对象初始化,并解释了如何遍历和操作这些列表。
摘要由CSDN通过智能技术生成

In this article, we’ll take a look at using initializer lists in C++ (std::initializer_list).

在本文中,我们将介绍如何在C ++中使用初始化列表( std::initializer_list )。

Whenever you implement your own Class, you probably want a way to initialize objects directly, using a list type format (using {}).

每当实现自己的Class时,您可能都想要一种使用列表类型格式(使用{} )直接初始化对象的方法。

Initializer Lists can achieve this and make your life a bit easier.

初始化列表可以实现这一点,并使您的生活更轻松。

NOTE: This is not to be confused with another topic, called as Member Initializer Lists

注意 :这不要与另一个主题,称为成员初始化程序列表混淆



了解初始化程序列表 (Understanding Initializer Lists)

An initializer list is a Class, which is defined in the <initializer_list.h> header file. To use this, we must include this header file.

初始化列表是Class ,它在<initializer_list.h>头文件中定义。 要使用此文件,我们必须包含此头文件。

This is also a template class, so we can pass any type to it, as a template parameter.

这也是模板类,因此我们可以将任何类型作为模板参数传递给它。


template <class Type>
class initializer_list

Here, Type is the template parameter that we pass to the class.

在这里, Type是我们传递给类的模板参数。

This class is also defined under the namespace std (the standard namespace). So, the full canonical path of this class will be: std::initializer_list.

此类也在名称空间 std (标准名称空间)下定义。 因此,此类的完整规范路径为: std::initializer_list

Let’s look at some simple examples using std::initializer_list.

让我们看一些使用std::initializer_list简单示例。

To declare an object of this type, we can initialize using the{} notation and use the auto keyword for automatic type inference.

要声明此类型的对象,我们可以使用{}表示法进行初始化,并使用auto关键字进行自动类型推断。


#include <iostream>
#include <string>
#include <initializer_list>

int main() {
    // Declare an object of initializer_list
    auto init_list = { 1, 2, 3, 4, 5 };

    // Using std::string as a template argument for the initializer list
    std::initializer_list<std::string> il = { "Hello", "from", "JournalDev" };

    return 0;
}

Here, we’ve created two objects of the std::initializer_list<> type.

在这里,我们创建了两个std::initializer_list<>类型的对象。

The template argument of the first object is automatically derived using auto, while we explicitly mention it in the second one, since we don’t use auto.

第一个对象的模板参数是使用auto自动派生的,而我们在第二个对象中明确提到了它,因为我们不使用auto

为什么我们要使用初始化列表? (Why do we want to use initializer lists?)

The advantage of these lists is that you can iterate through it, using the list.begin(), list.end(), and list.size() methods, so it is similar to a vector.

这些列表的优点是,您可以使用list.begin()list.end()list.size()方法进行遍历,因此它类似于vector

The list of methods is shown in a sample screenshot of the initializer_list.h file on Linux.

方法列表显示在Linux上的initializer_list.h文件的示例屏幕快照中。

Initializer List Header
Initializer List Header
初始化列表标题
Method NameWhat does it do?
initializer_list.size()Returns the size of the list (Similar to vector.size())
initializer_list.begin()Returns an iterator to the first element of the list (Similar to vector.begin())
initializer_list.end()Returns an iterator to an element after the last element of the list (Similar to vector.end())
方法名称 它有什么作用?
initializer_list.size() 返回列表的大小(类似于vector.size()
initializer_list.begin() 返回列表的第一个元素的迭代器(类似于vector.begin()
initializer_list.end() 返回列表的最后一个元素之后的元素的迭代器(类似于vector.end()

As you can see, it has methods like size(), begin() and end(), which are necessary for iterating through the list.

如您所见,它具有size(), begin()end() ,这些方法对于遍历列表是必需的。

To see how this works in action, we need to create a class, and pass this initializer list to it’s constructor.

要查看其工作原理,我们需要创建一个类,并将此初始值设定项列表传递给它的构造函数。


#include <iostream>
#include <initializer_list>

template <typename T>
class MyClass {
    public:
        MyClass(std::initializer_list<T> init_list) {
            // We can iterate through the initializer list
            for (auto it = init_list.begin(); it != init_list.end(); ++it) std::cout << *it << std::endl;
        }
};

This class must also be a template class, since the initializer list takes template arguments.

此类也必须是模板类 ,因为初始化列表使用模板参数。

So let’s call our template class MyClass.

因此,我们将其称为模板类MyClass


template <typename T>
class MyClass {
    public:
        int value;
        // Default constructor
        MyClass() { std::cout << "Default constructor\n"; value = -1; }
        
        // Parametrized constructor
        MyClass(int b = 100) { std::cout << "Parametrized constructor\n"; value = b; }

        // Constructor using std::initializer_list
        MyClass(std::initializer_list<T> init_list) {
            std::cout << "Initializer List Constructor\n";
            std::cout << "Iterating through the initializer_list<>\n";
            for (auto it = init_list.begin(); it != init_list.end(); ++it) {
                std::cout << "Current element in list = " << *it << std::endl;
            }
            // Set value = 20;
            value = 20;
        }
};

This takes in a template argument T, and sets value to specific values depending on the constructor called.

这接受模板参数T ,并根据所调用的构造函数将value设置为特定值。

To use initializer lists, we must create a constructor with std::initializer_list<T> as an argument. We can then iterate through this list and assign it to objects.

要使用初始化程序列表,我们必须使用std::initializer_list<T>作为参数创建一个构造函数。 然后,我们可以遍历此列表并将其分配给对象。

For the sake of this article, we’ll simply print the items of the list.

为了本文的方便,我们将仅打印列表中的项目。

Let’s see the complete program now.

现在让我们看看完整的程序。


#include <iostream>
#include <string>
#include <initializer_list>

template <typename T>
class MyClass {
    public:
        int value;
        // Default constructor
        MyClass() { std::cout << "Default constructor\n"; value = -1; }
        
        // Parametrized constructor
        MyClass(int b = 100) { std::cout << "Parametrized constructor\n"; value = b; }

        // Constructor using std::initializer_list
        MyClass(std::initializer_list<T> init_list) {
            std::cout << "Initializer List Constructor\n";
            std::cout << "Iterating through the initializer_list<>\n";
            for (auto it = init_list.begin(); it != init_list.end(); ++it) {
                std::cout << "Current element in list = " << *it << std::endl;
            }
            // Set value = 20;
            value = 20;
        }
};

int main() {
    // Declare an object of initializer_list
    auto init_list = { 1, 2, 3, 4, 5 };

    // Using std::string as a template argument for the initializer list
    std::initializer_list<std::string> il = { "Hello", "from", "JournalDev" };

    MyClass<int> my_obj = MyClass<int>(500);

    // Create an instance of MyClass using initializer lists
    MyClass<std::string> my_obj_il = { il };

    std::cout << "Value of normal instance: " << my_obj.value << std::endl;

    std::cout << "Value of instance constructed using initializer_list: " << my_obj_il.value << std::endl;

    return 0;
}

Here, we construct an object using initializer_list using this call:

在这里,我们使用此调用使用initializer_list构造一个对象:


std::initializer_list<std::string> il = { "Hello", "from", "JournalDev" };

The initializer list constructor will be invoked at this line.

初始化列表构造函数将在此行调用。

Output

输出量


Parametrized constructor
Initializer List Constructor
Iterating through the initializer_list<>
Current element in list = Hello
Current element in list = from
Current element in list = JournalDev
Value of normal instance: 500
Value of instance constructed using initializer_list: 20

Indeed, our output seems to confirm what we want! We’ve finally made use of std::initializer_list to initialize objects!

确实,我们的输出似乎证实了我们想要的! 我们终于利用了std::initializer_list来初始化对象!



结论 (Conclusion)

In this article, we learned how we can use initializer lists in C++.

在本文中,我们学习了如何在C ++中使用初始化列表。



参考资料 (References)



翻译自: https://www.journaldev.com/37427/initializer-lists-in-c-plus-plus

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值