📜  C++ : List的不同初始化方法

📅  最后修改于: 2020-09-08 07:45:47             🧑  作者: Mango

在本文中,我们将讨论在C++中初始化std :: list的不同方法;std :: list提供了各种重载的构造函数,用于列表的创建和初始化。

1.创建一个空List

// Create an empty list of ints
std::list listOfInts;

#include 
#include 

int main() {
// Create an empty list of ints
std::list listOfInts;

// Push back 10 elements in the list
for (int i = 0; i < 10; i++)
listOfInts.push_back(i);

// Iterate over the list and display numbers
for (int val : listOfInts)
std::cout << val << ",";
std::cout << std::endl;

return 0;
}

2. 指定List的大小和初始值

#include 
#include 
int main() {
    // Create a list and initialize it with 5 elements of value 119
    std::list listOfInts(5, 119);
    // Iterate over the list and display numbers
    for (int val : listOfInts)
        std::cout << val << ",";
    std::cout << std::endl;
    return 0;
}

它将创建一个包含5个元素的列表,每个元素都使用作为第二个参数(在本例中为119)传递的元素的副本进行初始化。

3. 指定初始化的元素

#include 
#include 
#include 
int main() {
    // Create a list and initialize it initializer_list of 7 elements
    std::list listOfInts( { 2, 8, 7, 5, 3, 1, 4 });
    // Iterate over the list and display numbers
    for (int val : listOfInts)
        std::cout << val << ",";
    std::cout << std::endl;
    // Create a initializer list of strings
    std::initializer_list initLits = { "Hi", "this", "is", "sample" };
    // Create & Initialize a list with initializer_list object
    std::list listOfStrs(initLits);
    // Iterate over the list and display strings
    for (std::string data : listOfStrs)
        std::cout << data << std::endl;
    return 0;
}

4. 使用一个List初始化对象

#include 
#include 
#include 
int main() {
    std::vector vecOfInt( { 2, 8, 7, 5, 3, 1, 4 });
    // Create a list and initialize it with vector
    std::list listOfInts(vecOfInt.begin(), vecOfInt.end());
    // Iterate over the list and display numbers
    for (int val : listOfInts)
        std::cout << val << ",";
    std::cout << std::endl;
    return 0;
}