Home
Aptitude
Categories


Home » C++ STL

Remove all occurrences of an element and remove set of some specific from the list | C++ STL



Example of list.remove() and list.remove_if() in C++ STL: Here, we are going to learn how to remove all occurrences of an element from the list and remove set of some of the specific elements from the list?
Submitted by IncludeHelp, on October 31, 2018

list.remove() and list.remove_if() functions

remove() function is used to remove all occurrences of a given element from the list and function remove_if() is used to remove set of some specific elements from the list.

Example:

    List elements are
    11
    22
    33
    44
    55
    11
    22

    Element to remove: 11

    List element after removing 11
    22
    33
    44
    55
    22

    Condition to remove some specific elements: all ODD numbers
    List element after removing all ODD numbers
    22
    44
    22

Program:

#include <iostream>
#include <list>
using namespace std;

int main() 
{
	//declaring a list 
	list<int> iList = {11, 22, 33, 44, 55, 11, 22};
	//declaring iterator to the list
	list<int>::iterator l_iter;

	//printing list elements
	cout<<"List elements are"<<endl;
	for (l_iter = iList.begin(); l_iter != iList.end(); l_iter++)
		cout<< *l_iter<<endl;

	//remove 11 from the List
	iList.remove(11);
	cout<<"List elements after removing 11"<<endl;
	for (l_iter = iList.begin(); l_iter != iList.end(); l_iter++)
		cout<< *l_iter<<endl;

	//remove all ODD numbers
	iList.remove_if([](int n){return (n%2!=0); });
	cout<<"List elements after removing all ODD numbers"<<endl;
	for (l_iter = iList.begin(); l_iter != iList.end(); l_iter++)
		cout<< *l_iter<<endl;

	return 0;
}

Output

List elements are
11
22
33
44
55
11
22
List elements after removing 11
22
33
44
55
22
List elements after removing all ODD numbers
22
44
22





Comments and Discussions

Ad: Are you a blogger? Join our Blogging forum.





Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing » Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates

© https://www.includehelp.com some rights reserved.