erase if

This is an example that combines the two linear find and erase algorithms.

= erase_if.hpp =

This header file is all you need.


 * 1) ifndef EFNETCPP_ERASE_IF_HPP_20110208T194936
 * 2) define EFNETCPP_ERASE_IF_HPP_20110208T194936


 * 1) include
 * 2) include

namespace efnetcpp { /** Version for most containers. */ template  struct tagged_erase { static void erase(C &c, typename C::const_reference x) { typename C::iterator i = c.begin; while (i != c.end) { typename C::iterator cur = i++; if (*cur == x) c.erase(cur); }   }

template  static void erase_if(C &c, Pr pr) { typename C::iterator i = c.begin; while (i != c.end) { typename C::iterator cur = i++; if (pr(*cur)) c.erase(cur); }   } };

/** Version for random-access containers. */ template  struct tagged_erase { static void erase(C &c, typename C::const_reference x) { c.erase(std::remove(c.begin, c.end, x), c.end); }

template < typename Pr > static void erase_if(C &c, Pr pr) { c.erase(std::remove_if(c.begin, c.end, pr), c.end); } };

template  void erase_if(C &c, Pr pr) { tagged_erase::erase_if(c, pr); }

template < typename C > void erase(C &c, typename C::const_reference x) { tagged_erase::erase(c, x); } } // efnetcpp


 * 1) endif

= Test harness =

This shows how it is used.


 * 1) include "erase_if.hpp"


 * 1) include
 * 2) include
 * 3) include
 * 4) include
 * 5) include
 * 6) include
 * 7) include
 * 8) include

bool is_even(int n) { return n % 2 == 0; }

template < typename C > void test { C act; for (int i = 0; i < 10; ++i) act.insert(act.end, i);

efnetcpp::erase_if(act, &is_even); efnetcpp::erase(act, 3);

C exp; for (int i = 0; i < 10; ++i) { if (!(i == 3 || is_even(i))) exp.insert(exp.end, i); }   assert(exp == act); }

int main { using namespace std; test< vector >; test< basic_string >; test< deque >; test< list >; test< multiset >; test< set >; }