std::list::remove_if predicate

By , last updated May 17, 2016

Recall, that std:remove_if predicate won’t actually remove the elements from a container unless it’s a member of a container, like std::list::remove_if. In this case the elements will be removed.

Let us take a look at an example of a predicate to be used with std::list::remove_if.

First, we create a template class CHECK_RETIRE.

template <class T> class CHECK_RETIRE : public std::unary_function<T,bool>
		time_t now;
		CHECK_RETIRE(time_t n) : now (n) { }

		bool operator() ( T val )
			// T is a shared_ptr. If the member ->retire is less than now, return true to remove me.
			return val->retire < now;

Here is an example of how such class template can be used in the code:

struct CHECK
	time_t retire;

typedef boost::shared_ptr<CHECK>	 CHECK_ptr;

std::list<CHECK> checklist:

Now we would like to remove all items with the member retire less than 1000:

time_t now = 1000;
checklist.remove_if( CHECK_RETIRE<CHECK>(now) );

Items with ->retire less than 1000 is now removed from the list.


Be the first to comment.

Leave a Reply

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>