C++ Standard List Insert() Examples

Updated on January 16, 2018
sirama profile image

I am a software engineer. I have been working with C++, MFC, and .net technologies for 15 Yrs. I like playing video games & reading books.

1. Introduction

The "insert()" function of the standard list is used to insert new elements to the existing list. While inserting a new element we need to specify the position and value and we will see an example for each available overload here one-by-one.

2. Supporting functions for this Hub

Before we move to our example, let us see two helper function which we are going to use throughout this example. The function Add_ListElements() is written to add default elements to the list. It adds 1,2,3,4,5,6 to the list. Below is the function:


Listing 1.1

//ListInsert 01: Function to Push some values to List
void Add_ListElements(list<int>& listParam)
{
	listParam.clear();
	listParam.push_back(1);
	listParam.push_back(2);
	listParam.push_back(3);
	listParam.push_back(4);
	listParam.push_back(5);
	listParam.push_back(6);
}

The Print_List() function will iterate through the supplied list and prints the content to the console output window. Below is the function:


Listing 1.2

//ListInsert 02: Function to Print the Values in List
void Print_List(list<int> listParam)
{
	list<int>::iterator listItr;
	printf("\nThe contents of the Lists are:\n");
	for (listItr = listParam.begin();
		listItr != listParam.end();
		listItr++)
		printf("[%d] ", *listItr);
}

3. Inserting single element to a List

To insert a single element to the list we have to use below specified overload of the insert function:

iterator insert(const_iterator _Where, _Ty&& _Val)

Here, "_Where" parameter is expecting the position in which the new element needs to be inserted. The second parameter _Val is the value that we want to insert. Now have a look the below piece of code:

Listing 1.3

//3.1 Create list and iterator
list<int> theList;
Add_ListElements(theList);
Print_List(theList);

//3.2 Position the Iterator for Insertion
list<int>::iterator Position;
Position = theList.begin();
Position++;
Position++;

//3.3 Insert an element and print the list
printf("\nAfter inserting the Single Element,");
Position = theList.insert(Position, 7);
Print_List(theList);

In code snippet 3.1, we created the list and added six default element to it by calling the Add_ListElements() (Listing 1.1) function. Then we printed the content of the list.

In code snippet 3.2, we got the iterator for the list by calling the begin() function and moved it twice in steps by performing the increment operation ++. Now, the iterator is pointing at the third element 3. This is shown in the below depiction:


Inserting single element to standard list
Inserting single element to standard list | Source

In code snippet 3.3, we are calling the insert function by supplying the position and the value which is 7. The call will add a new element in the current position and shifts the remaining elements towards the right of it. In the above picture the newly inserted element is shown as green and shifted elements are shown in yellow.

4. Inserting Multiple Elements

The standard list's insert function expects three parameters to insert multiple elements in it. The first parameter tells the position in the list from where the insertion starts. The second parameter tells, how elements needs to be inserted. The third parameter is the actual value that needs to be inserted. The below picture shows inserting three elements of value 11 at the position which is given as first parameter:


Std::list::Insert() to insert multiple values
Std::list::Insert() to insert multiple values | Source

Note that even though we insert multiple values, all the values are same and occupied contiguous location in the list.Now, have a look the sample code below:

Listing 1.4

//3.4 Insert multiple elements from current position
printf("\nAfter inserting the three Elements(Val 11),");
Position = theList.insert(Position, 3, 11);
Print_List(theList);

Here, at line three we are inserting 3 elements with the value 11. And, in the next line we are printing the list to the console output window. This insertion is depicted as shown below:

Inserting multiple elements to standard c++ list
Inserting multiple elements to standard c++ list | Source

Note that before the insert call, the iterator "Position" is at element 7 (Third position in the list). After the call to insert, three elements are added at this position and all the existing elements including 7 are shifted left. The newly added elements are shown in green and shifted elements are show in yellow.

5. Copy elements between list

Using the Standard list insert method, one can copy the list elements from some other list as well. The function's parameter list is shown below:


Copy elements between list - Parameter details
Copy elements between list - Parameter details | Source

The first parameter "Position" denotes the copy location in the destination list. The second and third parameter tells the start and end position from the source list and this will tell what range of elements should be copied from source to destination. Now, have a look at the below code:

Listing 1.5

//3.5 Insert Elements from another list (Copy)
//3.5.1 Create the Source List and set the Iterator
//		position
list<int> SecondList;
Add_ListElements(SecondList);
list<int>::iterator Start = SecondList.begin();
list<int>::iterator End = SecondList.end();
Start++;
Start++;
End--;
End--;

Here, the source list is prepared for our example. In line 4,5 a list is created and default elements 1,2,3,4,5,6 is added to it. At line 6 and 7, we grabbed the list iterator which points to start and end of the list. In line 8-11, we re-positioned the start and end iterator so that only two elements copied to the destination list.

Now look at the code below which copies the list elements from "SecondList":

Listing 1.6

//3.5.2 Copy the source elements to destination
Position++;
theList.insert(Position, Start, End);
printf("\nAfter inserting the Elements from Second List,");
Print_List(theList);

Note that we moved the iterator by one element (Line 2) from its current position. Refer the previous picture and we can say the Position now points to 4th element in the list. At line 3, we called the insert function which actually performs a copy from source to destination. This is depicted below:

Copy elements between C++ List
Copy elements between C++ List | Source

Once the list elements are copied, the content of the destination list is printed in the console output window. The complete example and its output is shown below:

Completed Example

#include <stdio.h>
#include <conio.h>
#include <list>

using namespace std;

//ListInsert 01: Function to Push some values to List
void Add_ListElements(list<int>& listParam)
{
	listParam.clear();
	listParam.push_back(1);
	listParam.push_back(2);
	listParam.push_back(3);
	listParam.push_back(4);
	listParam.push_back(5);
	listParam.push_back(6);
}

//ListInsert 02: Function to Print the Values in List
void Print_List(list<int> listParam)
{
	list<int>::iterator listItr;
	printf("\nThe contents of the Lists are:\n");
	for (listItr = listParam.begin();
		listItr != listParam.end();
		listItr++)
		printf("[%d] ", *listItr);
}

//ListInsert 03: Clear List through Remove_if and Predicates
void main()
{
	//3.1 Create list and iterator
	list<int> theList;
	Add_ListElements(theList);
	Print_List(theList);

	//3.2 Position the Iterator for Insertion
	list<int>::iterator Position;
	Position = theList.begin();
	Position++;
	Position++;

	//3.3 Insert an element and print the list
	printf("\nAfter inserting the Single Element,");
	Position = theList.insert(Position, 7);
	Print_List(theList);

	//3.4 Insert multiple elements from current position
	printf("\nAfter inserting the three Elements(Val 11),");
	Position = theList.insert(Position, 3, 11);
	Print_List(theList);

	//3.5 Insert Elements from another list (Copy)
	//3.5.1 Create the Source List and set the Iterator
	//		position
	list<int> SecondList;
	Add_ListElements(SecondList);
	list<int>::iterator Start = SecondList.begin();
	list<int>::iterator End = SecondList.end();
	Start++;
	Start++;
	End--;
	End--;

	//3.5.2 Copy the source elements to destination
	Position++;
	theList.insert(Position, Start, End);
	printf("\nAfter inserting the Elements from Second List,");
	Print_List(theList);

	_getch();
}
Output of Sta::List::Insert Example
Output of Sta::List::Insert Example | Source

Comments

    0 of 8192 characters used
    Post Comment

    No comments yet.

    working