stl list c++ – C++ : How to Copy / Clone a STL List or Sub List

stl list c++: In the previous article, we have discussed about C++11 Multithreading Tutorial PDF. Let us learn how to Copy / Clone a STL in C++ Program.

How to copy/clone a STL List or Sub List

In this article we will discuss about multiple techniques to clone the whole list or copy just a sub list. So, let’s explore the topic to know more about it.

We will use this list in the whole article and we will copy this or a sub list from this list.

// List of strings
std::list<std::string> listOfStrs = { "Goa", "Puri", "Pune", "Hyderabad", "Bhubaneswar", "Mumbai" };

Copying a std::list using Copy constructor :

A copy constructor is provided by std::list which clones a given to list to new list.

We can use this to copy whole content to a new list.

// all the contents copied from one list to another
std::list<std::string> listOfStrs_2(listOfStrs);

And the new list content will be same like

"Goa", "Puri", "Pune", "Hyderabad", "Bhubaneswar", "Mumbai"

Copying a range or sub list to std::list using parameterized constructor :

A parameterized constructor is provided by std::list  which accepts a range and copies all the elements to a new list coming within the range.

We can use this to copy elements coming under a range to a new list.

// copying all the contents within a range of one list to another
std::list<std::string> listOfStrs_3(listOfStrs.begin(), listOfStrs.end());

Here we have passed the range as beginning of old list to the end of old list as range. So it will copy all the elements of the old list to a new list.

And the new list content will be same like

"Goa", "Puri", "Pune", "Hyderabad", "Bhubaneswar", "Mumbai"

Copying a std::list using assignment operator :

An assignment operator std::list which copies all the contents of given list to a new list.

We can use this to copy elements to a new list.

// copying all the contents of one list to another list
std::list<std::string> listOfStrsCopy = listOfStrs;

And the new list content will be same like

"Goa", "Puri", "Pune", "Hyderabad", "Bhubaneswar", "Mumbai"

Copying a std::list or sub list using list::assign() :

A member function assign() is provided by std::list which accepts a range and copies the elements which are coming within that range to a new list.

// a new list of strings is created
std::list<std::string> listOfStrs_4;

//Using assign() function accepting a range
// Copying all the elements with in that range to new list.
listOfStrs_4.assign(listOfStrs.begin(), listOfStrs.end());

Here we have passed the range as beginning of old list to the end of old list as range. So it will copy all the elements of the old list to a new list.

And the new list content will be same like

"Goa", "Puri", "Pune", "Hyderabad", "Bhubaneswar", "Mumbai"