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

    This website uses cookies

    As a user in the EEA, your approval is needed on a few things. To provide a better website experience, turbofuture.com uses cookies (and other similar technologies) and may collect, process, and share personal data. Please choose which areas of our service you consent to our doing so.

    For more information on managing or withdrawing consents and how we handle data, visit our Privacy Policy at: https://turbofuture.com/privacy-policy#gdpr

    Show Details
    Necessary
    HubPages Device IDThis is used to identify particular browsers or devices when the access the service, and is used for security reasons.
    LoginThis is necessary to sign in to the HubPages Service.
    Google RecaptchaThis is used to prevent bots and spam. (Privacy Policy)
    AkismetThis is used to detect comment spam. (Privacy Policy)
    HubPages Google AnalyticsThis is used to provide data on traffic to our website, all personally identifyable data is anonymized. (Privacy Policy)
    HubPages Traffic PixelThis is used to collect data on traffic to articles and other pages on our site. Unless you are signed in to a HubPages account, all personally identifiable information is anonymized.
    Amazon Web ServicesThis is a cloud services platform that we used to host our service. (Privacy Policy)
    CloudflareThis is a cloud CDN service that we use to efficiently deliver files required for our service to operate such as javascript, cascading style sheets, images, and videos. (Privacy Policy)
    Google Hosted LibrariesJavascript software libraries such as jQuery are loaded at endpoints on the googleapis.com or gstatic.com domains, for performance and efficiency reasons. (Privacy Policy)
    Features
    Google Custom SearchThis is feature allows you to search the site. (Privacy Policy)
    Google MapsSome articles have Google Maps embedded in them. (Privacy Policy)
    Google ChartsThis is used to display charts and graphs on articles and the author center. (Privacy Policy)
    Google AdSense Host APIThis service allows you to sign up for or associate a Google AdSense account with HubPages, so that you can earn money from ads on your articles. No data is shared unless you engage with this feature. (Privacy Policy)
    Google YouTubeSome articles have YouTube videos embedded in them. (Privacy Policy)
    VimeoSome articles have Vimeo videos embedded in them. (Privacy Policy)
    PaypalThis is used for a registered author who enrolls in the HubPages Earnings program and requests to be paid via PayPal. No data is shared with Paypal unless you engage with this feature. (Privacy Policy)
    Facebook LoginYou can use this to streamline signing up for, or signing in to your Hubpages account. No data is shared with Facebook unless you engage with this feature. (Privacy Policy)
    MavenThis supports the Maven widget and search functionality. (Privacy Policy)
    Marketing
    Google AdSenseThis is an ad network. (Privacy Policy)
    Google DoubleClickGoogle provides ad serving technology and runs an ad network. (Privacy Policy)
    Index ExchangeThis is an ad network. (Privacy Policy)
    SovrnThis is an ad network. (Privacy Policy)
    Facebook AdsThis is an ad network. (Privacy Policy)
    Amazon Unified Ad MarketplaceThis is an ad network. (Privacy Policy)
    AppNexusThis is an ad network. (Privacy Policy)
    OpenxThis is an ad network. (Privacy Policy)
    Rubicon ProjectThis is an ad network. (Privacy Policy)
    TripleLiftThis is an ad network. (Privacy Policy)
    Say MediaWe partner with Say Media to deliver ad campaigns on our sites. (Privacy Policy)
    Remarketing PixelsWe may use remarketing pixels from advertising networks such as Google AdWords, Bing Ads, and Facebook in order to advertise the HubPages Service to people that have visited our sites.
    Conversion Tracking PixelsWe may use conversion tracking pixels from advertising networks such as Google AdWords, Bing Ads, and Facebook in order to identify when an advertisement has successfully resulted in the desired action, such as signing up for the HubPages Service or publishing an article on the HubPages Service.
    Statistics
    Author Google AnalyticsThis is used to provide traffic data and reports to the authors of articles on the HubPages Service. (Privacy Policy)
    ComscoreComScore is a media measurement and analytics company providing marketing data and analytics to enterprises, media and advertising agencies, and publishers. Non-consent will result in ComScore only processing obfuscated personal data. (Privacy Policy)
    Amazon Tracking PixelSome articles display amazon products as part of the Amazon Affiliate program, this pixel provides traffic statistics for those products (Privacy Policy)