Removing elements from a container - C++ STL

C++ examples for STL:list

Description

Removing elements from a container

Demo Code

#include <iostream>
#include <string>
#include <list>
#include <algorithm>
#include <functional>

using namespace std;

template<typename C>
void printContainer(const C& c, char delim = ',', ostream& out = cout) {
   printRange(c.begin(), c.end(), delim, out);
}

template<typename Fwd>
void printRange(Fwd first, Fwd last, char delim = ',', ostream& out = cout) {
   out << "{";
   while (first != last) {
      out << *first;/*  w  ww  .j a v a2s .  c  o m*/
      if (++first != last)
         out << delim << ' ';
   }
   out << "}" << endl;
}

int main() {

   list<string> lstStr;

   lstStr.push_back("a");
   lstStr.push_back("v");
   lstStr.push_back("c");
   lstStr.push_back("d");
   lstStr.push_back("e");

   list<string>::iterator p;

   // Find what you want with find
   p = find(lstStr.begin(), lstStr.end(), "day");

   p = lstStr.erase(p); // Now p points to the last element

   // Or, to erase all occurrences of something, use remove
   lstStr.erase(remove(lstStr.begin(), lstStr.end(), "cloudy"), lstStr.end());
   printContainer(lstStr);
}

Related Tutorials