ArtsAutosBooksBusinessEducationEntertainmentFamilyFashionFoodGamesGenderHealthHolidaysHomeHubPagesPersonal FinancePetsPoliticsReligionSportsTechnologyTravel

C++ std::list clear vs erase Explained with Examples

Updated on December 12, 2017
sirama profile image

I am a software engineer. I have been come across C++,MFC, .net technologies. I like playing video games & reading books.

1. Clearing all the std::List Elements through std::Clear()

The clear() function of the standard list removes all the elements stored in it and it leaves the list empty. This will make sure the destructor gets called when the list stores C++ objects or simply it destroys all the objects. Let us have a look at the below Code:

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

using namespace std;

//Example 01: Clear
void main()
{
	//1.0 Create list and iterator
	list<int> theList;
	list<int>::iterator listItr;

	//2.0 Let us push some elements to the List
	theList.push_back(2);
	theList.push_back(4);
	theList.push_back(6);
	theList.push_back(8);

	//3.0 Iterate the List and Show Elements in it
	printf("Total Elements in the List: %d\n", 
		theList.size());
	printf("The Content of List:\n");
	for (listItr = theList.begin(); 
	listItr != theList.end(); listItr++)
		printf("[%d] ", *listItr);

	//4.0 Clear the List
	printf("\nClearing the List");
	theList.clear();
	printf("\nTotal Elements in the List: %d\n",
		theList.size());

	//5.0 Let put two three elements
	printf("Adding three new int values\n");
	theList.push_back(12);
	theList.push_back(14);
	theList.push_back(16);
	printf("Total Elements in the List: %d\n", 
		theList.size());
	printf("The Content of List:\n");
	for (listItr = theList.begin(); 
		listItr != theList.end(); listItr++)
		printf("[%d] ", *listItr);
	_getch();
}

In the Above Example, a list is created and four elements namely 2,4,6,8 is pushed into it. In Code snippet 3.0, the "std::size()" method called on the list tells how many elements present in the list and also here we traverse the list through iterator to list all the elements.

Code snippet 4.0, makes a call to the "std::clear()" method. Once this method is called, all the elements in the lists are removed. In our case, the list elements 2,4,6,8 will be removed from the list.

Code Snippet 5.0 tells that calling clear destroys all the elements stored in the list and at the same time, the list still lives. Here, the same list is added with three new elements and then the elements are iterated to display its value in the console window.

The output of the above example shown below:

Pic1. Program output of Std::List::Clear Example
Pic1. Program output of Std::List::Clear Example | Source

2. The list::Empty

The empty() function of the standard list, check whether list is empty or not. It will not clear the items from the list. Have a look at the below example:

list::Empty Example
list::Empty Example | Source

In the above example, four integer elements 2,4,6,8 are added to the list. At this stage, the list is having four elements. The code marked as one, tests the list to see it is empty or not. The empty() function returns true when the list is empty. Here, in the example (Snippet, Marked as 1), it returns false as the list in not empty.

The code snippet 2 shows that the list is cleared by calling the std::list::clear() and all four integers removed from the list. Calling empty() function at this stage returns true to the caller as the list does not have any integer number(s) in it. The complete code example for list::Empty is given below:

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

using namespace std;

//Example 01: Clear
void main()
{
	//1.0 Create list and iterator
	list<int> theList;
	list<int>::iterator listItr;

	//2.0 Let us push some elements to the List
	theList.push_back(2);
	theList.push_back(4);
	theList.push_back(6);
	theList.push_back(8);

	//3.0 Iterate the List and Show Elements in it
	if (theList.empty())
		printf("The List is Empty\n");
	else
		printf("The List has element(s) in it\n");
	printf("Total Elements %d\n", theList.size());

	//4.0 Clear and test the list
	printf("Clearing the Elements\n");
	theList.clear();
	if (theList.empty())
		printf("The List is Empty\n");
	else
		printf("The List has element(s) in it\n");
	printf("Total Elements %d", theList.size());

	_getch();
}

The output of the above example is shown below:


Output of std::List::Empty Example
Output of std::List::Empty Example | Source

3. Removing Elements through std::list::erase

3.1 Removing Single Element

The Erase function is used to delete a single element or range of elements from the list. First, let us look at the example that erases single element from the list. Consider the code snippet below:


//1.0 Create list and iterator
list<int> theList;
list<int>::iterator listItr;

//2.0 Let us push some elements to the List
theList.push_back(2);
theList.push_back(4);
theList.push_back(6);
theList.push_back(8);
theList.push_back(10);
theList.push_back(12);
theList.push_back(14);
printf("Current List Elelements are: ");
for (listItr = theList.begin();
	listItr != theList.end(); listItr++)
	printf("[%d] ", *listItr);

In the above code, we added 7 integer elements to the list. After that we displayed the list elements in the list on console output window. Now, look at the below code:

//3.0 Remove a single Element from the List
listItr = theList.begin();  
listItr++;
listItr++;

We got a list iterator pointing to the first element in the list by calling the function begin(). Then incremented the list iterator twice and now, the iterator is pointing to the third element in the list. This shown in the below picture:


Pic 1. list::erase - Single Element
Pic 1. list::erase - Single Element | Source

At this stage if we call the erase function by passing the iterator as parameter, the element pointed by it will be removed from the list. In our Example, the third list element (Value 6) gets removed after calling the std::list::erase(<list Iterator>) function. Below is the code snippet:

theList.erase(listItr);
printf("\nList Elelements After Erasing Single Element: ");
for (listItr = theList.begin();
	listItr != theList.end(); listItr++)
	printf("[%d] ", *listItr);

3.2 Erasing Range of elements from the List

To remove range of continuous list elements we need to iterators. One iterator tells where the removal should start and another one tells where it ends. Have a look at the below piece of code:

list<int>::iterator listItrBack = theList.begin();
list<int>::iterator listItrFront = theList.begin();
listItrBack++; listItrBack++;
listItrFront = listItrBack;
listItrBack++; listItrBack++; listItrBack++;

At this stage, listItrFront points to the third element in the List and listItrBack points to the last element in the list. For Example, if read the values through the iterator values now, listItrFront gives 8 and listItrBack gives 14. This is illustrated in the below picture. When we call list::erase by passing these two iterators as parameters, the items highlighted in Red gets removed from the list.

Pic: Erasing range of element from C++ List
Pic: Erasing range of element from C++ List | Source

Now look at the below piece of code. Here, we are calling std::list::Erase by passing the two iterators to it. After the call, the elements highlighted in the picture above will get removed. The code snippet is shown below:

//4.0 Remove Range of Elements
list<int>::iterator listItrBack = theList.begin();
list<int>::iterator listItrFront = theList.begin();
listItrBack++; listItrBack++;
listItrFront = listItrBack;
listItrBack++; listItrBack++; listItrBack++;
theList.erase(listItrFront, listItrBack);
printf("\nList Elelements After Erasing Range of Elements: ");
for (listItr = theList.begin();
	listItr != theList.end(); listItr++)
	printf("[%d] ", *listItr);

The complete example and its output is given below:

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

using namespace std;

//Example 01: Clear
void main()
{
	//1.0 Create list and iterator
	list<int> theList;
	list<int>::iterator listItr;

	//2.0 Let us push some elements to the List
	theList.push_back(2);
	theList.push_back(4);
	theList.push_back(6);
	theList.push_back(8);
	theList.push_back(10);
	theList.push_back(12);
	theList.push_back(14);
	printf("Current List Elelements are: ");
	for (listItr = theList.begin();
		listItr != theList.end(); listItr++)
		printf("[%d] ", *listItr);

	//3.0 Remove a single Element from the List
	listItr = theList.begin();  
	listItr++;
	listItr++;
	theList.erase(listItr);
	printf("\nList Elelements After Erasing Single Element: ");
	for (listItr = theList.begin();
		listItr != theList.end(); listItr++)
		printf("[%d] ", *listItr);

	//4.0 Remove Range of Elements
	list<int>::iterator listItrBack = theList.begin();
	list<int>::iterator listItrFront = theList.begin();
	listItrBack++; listItrBack++;
	listItrFront = listItrBack;
	listItrBack++; listItrBack++; listItrBack++;
	theList.erase(listItrFront, listItrBack);
	printf("\nList Elelements After Erasing Range of Elements: ");
	for (listItr = theList.begin();
		listItr != theList.end(); listItr++)
		printf("[%d] ", *listItr);


	_getch();
}
Pic: Erase Range of C++ List Elements - Program Output
Pic: Erase Range of C++ List Elements - Program Output | 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, hubpages.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://hubpages.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)