How to Copy a List in C++ STL?

In C++, a list is a sequence container provided by the STL library that represents a doubly linked list and allows us to store data in non-contiguous memory locations efficiently. In this article, we will learn how to copy one list to another in C++.

Input: 
sourceList = {10, 20, 30, 40, 50};

Output:
copiedList = {10, 20, 30, 40, 50};

Copying a List to Another List in C++

To copy a std::list in C++, we can use the default copy constructor which creates a new list that is a copy of an existing list with the same type. It automatically copies all elements from the original list to the new list, maintaining the order. we just have to invoke the copy constructor by passing the source list as an argument.

Syntax to Copy a List

list<dataType> copiedList(existingList);

Here,

  • dataType is the type of the elements stored in the list.
  • copiedList is the new list that we are creating.
  • sourceList is the existing list from which we want to create a copy.

C++ Program to Copy One List to Another

The below program demonstrates how we can copy a std::list to another list in C++.

C++
// C++ program to copy a list to another list

#include <iostream>
#include <list>
using namespace std;

int main()
{
    // Creating and initializing an source list
    list<int> sourceList = { 1, 2, 3, 4, 5 };

    // Creating a copied list using the copy constructor
    list<int> copiedList(sourceList);

    // Output the contents of the copied list
    cout << "Copied List: ";
    for (int num : copiedList) {
        cout << num << " ";
    }
    cout << endl;

    return 0;
}

Output
Copied List: 1 2 3 4 5 

Time Complexity: O(N), where N denotes the size of the list.
Auxiliary Space: O(N)