×

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.

Examples of list.remove_if() function | C++ STL

Here, we are implementing program that will demonstrate the example of remove_if() function, which is used to remove a set of elements which satisfy the given test condition.
Submitted by IncludeHelp, on October 31, 2018

Examples of list.remove_if() function

Here, we have a list of the integers and performing remove operations based on following given test conditions:

  1. Remove all negative elements
  2. Remove all elements which are divisible by 11
  3. Remove all elements which are greater than 20

C++ program to implement examples of list.remove_if() function

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

// function to display the list
void dispList(list<int> L) {
  // declaring iterator to the list
  list<int>::iterator l_iter;
  for (l_iter = L.begin(); l_iter != L.end(); l_iter++) cout << *l_iter << " ";
  cout << endl;
}

int main() {
  // declaring a list
  list<int> iList = {10, 20, 11, 22, 21, -10, -20, 13, 55, 44};

  // printing list elements
  cout << "List elements are" << endl;
  dispList(iList);

  // remove only negative numbers
  iList.remove_if([](int n) { return (n < 0); });
  cout << "List elements after removing Negative elements" << endl;
  dispList(iList);

  // remove the elements which are divisible by 11
  iList.remove_if([](int n) { return (n % 11 == 0); });
  cout << "List elements after removing divisble by 11" << endl;
  dispList(iList);

  // remove the elements which are greater than 20
  iList.remove_if([](int n) { return (n > 20); });
  cout << "List elements after removing greater than 20" << endl;
  dispList(iList);

  return 0;
}

Output

List elements are
10 20 11 22 21 -10 -20 13 55 44
List elements after removing Negative elements
10 20 11 22 21 13 55 44
List elements after removing divisble by 11
10 20 21 13
List elements after removing greater than 20
10 20 13

Comments and Discussions!

Load comments ↻





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