In this article we will discuss different techniques to clone the whole list or copy just a sub list.

Suppose we have a std::list of strings i.e.

Now let’s see how to copy this or a sub list from this list,

Copy a std::list using Copy constructor

std::list provides a copy constructor that clones a given to list to new list i.e.

We can use it to copy complete list while creating a new list i.e.

New list contents will be,

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

std::list provides a parameterized constructor that accepts a range and copies all the elements in given range to the new list.

We can use it to copy complete list or any sub list while creating a new list i.e.

New list contents will be,

 Copy a std::list using assignment operator

std::list provides an assignment operator that that copies all the contents of given list to the existing list i.e.

We can use it to copy complete list while creating a new list i.e.

New list contents will be,

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

std::list provides a member function assign(),

It accepts a range and copies all the elements in given range to the existing list by replacing it contents.

We can use it to copy complete list to the existing list i.e.

New list contents will be,

Copying a sub list using list::assign(),

Let’s Copy 2 elements from index 1 and 2 to the new list using std::list::assign()

New list contents will be,

 Copy a std::list or sub list using std::copy()

We can use STL algorithm to copy a range from a list i.e. a sub list or complete list to the another list i.e.

Let’s Copy 2 elements from index 1 and 2 to the new list using std::copy

New list contents will be,

 Copy a condition based sub list to std::list using std::copy_if() & Lambda Function

We can use STL algorithm to copy a only selective elements from a list to the another list i.e,

Copy string elements with size 2 from existing list to the new list using std::copy(),

New list contents will be,

Complete example is as follows,

Output:

 

 

Click Here to Subscribe for more Articles / Tutorials like this.