Initializing from another List

Another way to initialize a list is to use another list. In this, we provide iterators of the old list as arguments. The syntax for this is given below.

Syntax:

list<data_type>li(old_list.begin(),old_list.end()); 

Example:

C++




// C++ program to initialize the List
// from another List
#include<bits/stdc++.h>
using namespace std;
 
int main()
{
    // Initialising first list
    list<int> vect{ 10, 20, 30 };
    
    // Initialising the second list
    // from the first list
    list<int> li(vect.begin(), vect.end());
     
    // Printing the second List
    for (int x : li)
        cout << x << " ";
 
    return 0;
}


Output

10 20 30 

Different Ways to Initialize a List in C++ STL

Prerequisite: List in C++

Lists are sequence containers that allow non-contiguous memory allocation The following are the different ways to create and initialize a List in C++ STL.

  1. Initializing an empty List and pushing values one by one
  2. Specifying List size and initializing all values
  3. Initializing List like the arrays
  4. Initializing a list from an array
  5. Initializing a list from a vector
  6. Initializing a list from another List
  7. Initializing the List using the fill() function
  8. Using a lambda expression and the generate() function:

Similar Reads

1. Initializing an empty List and pushing values one by one

The standard way to initialize a list is to first create an empty list and then elements are added to that list using the inbuilt list_name.push_back() method....

2. Specifying List size and initializing all values

...

3. Initializing List like the arrays

Another way to initialize a list is by assigning a particular value to all the elements of the list. In this method, we pass a desired size for the list and the value to be stored for all the elements of that size....

4. Initializing a list from an array

...

5. Initializing a list from a vector

Another way of initialization is by passing a predetermined list of elements (initializer list) as an argument. The syntax for this method is shown below:...

6. Initializing from another List

...

7. Initializing the List using the fill() function

One can also initialize the list from an array with the same data type....

8. Using a lambda expression and the generate() function:

...