philgates

philgates philgates

Niner since 2010

Comments

  • C9 Lectures: Stephan T. Lavavej - Standard Template Library (STL), 2 of n

  • C9 Lectures: Stephan T. Lavavej - Standard Template Library (STL), 2 of n

    Great stuff!

    Here's the solution I came up with for what NotFredSafe called erase_if().

    This does not work for set, multiset, unordered_set, or unordered_multiset!

     

    #include <algorithm> #include <iterator> #include <utility> using namespace std;
    template<class IterTag, class ValueType> struct remover { template<class Container, class IterType, class Predicate> static void do_remove_if(Container &c, IterType begin, IterType end, Predicate pred) { c.remove_if(pred); } };
    template<class ValueType> struct remover<random_access_iterator_tag, ValueType> { template<class Container, class IterType, class Predicate> static void do_remove_if(Container &c, IterType begin, IterType end, Predicate pred) { c.erase(remove_if(begin, end,
     pred), end); } };
    template<class IterTag, class Key, class Value> struct remover<IterTag, pair<Key, Value>> { template<class Container, class IterType, class Predicate> static void do_remove_if(Container &c, IterType begin, IterType end, Predicate pred) { for(auto i = c.begin();
     i != c.end();) { if(pred(*i)) c.erase(i++); else ++i; } } }; 
    template<class Container, class Predicate> void erase_if(Container &c, Predicate pred) { typedef iterator_traits<Container::iterator>::iterator_category iter_cat_t; typedef remover<iter_cat_t, Container::value_type> remover_t; remover_t::do_remove_if(c,
     c.begin(), c.end(), pred); } 

     

    The remover struct provides the template machinery so that there only needs to be one definition of erase_if(). I prefer this to having an overload for each container type, although the fact that it doesn't work for the set containers shows that this isn't the perfect solution either Wink

     

    It would be nice to have a more comprehensive set of traits classes in the STL to make writting this kind of code easier.