A RetroSearch Logo

Home - News ( United States | United Kingdom | Italy | Germany ) - Football scores

Search Query:

Showing content from https://www.geeksforgeeks.org/cpp/how-to-copy-a-list-in-cpp/ below:

How to Copy a List in C++ STL?

How to Copy a List in C++ STL?

Last Updated : 23 Jul, 2025

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,

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)



RetroSearch is an open source project built by @garambo | Open a GitHub Issue

Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo

HTML: 3.2 | Encoding: UTF-8 | Version: 0.7.4