×

C++ STL Tutorial

C++ STL Algorithm

C++ STL Arrays

C++ STL String

C++ STL List

C++ STL Stack

C++ STL Set

C++ STL Queue

C++ STL Vector

C++ STL Map

C++ STL Multimap

C++ STL MISC.

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.

Here is an example with sample input and output:

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

C++ program to remove all occurrences of an element and remove set of some specific from the list

#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!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.