Chris Smith on Fri, 19 Mar 2004 16:30:11 -0600 (CST) |
[Date Prev] [Date Next] [Thread Prev] [Thread Next] [Date Index] [Thread Index]
[ALACPP] copy_if? |
So, I was coding late one night, and I wanted something like Smalltalk's "select:" method. For those of you who aren't familiar with Smalltalk, it basically allows you to create a select from a collection those elements which meat a criteria (when thrown throw a single argument block they evaluate to true... this is the equivalent of a Predicate in the C++ world). You get back a new collection which contains just the elements that meet the criteria. I figured there had to be something like this in the STL, but surprisingly couldn't find anything. I had a number of near misses, but it seemed this would be a common enough case that it would actually make it in. I ended up coding up the following: template<typename InputIterator, typename OutputIterator, typename Predicate> inline OutputIterator copy_if(InputIterator first, InputIterator last, OutputIterator result, Predicate pred) { //we could use foreach, but that would require //creating another predicate for the code inside the while //and I'm far too lazy for that while (first != last) { if (pred(*first)) { result++ = *first; } ++first; } return result; } It seems to work for me. Anyone have thoughts as to: a) If there is something in the STL that does this just as well as my copy_if, and I'm just woefully ignorant. b) Why this would not be included in the STL, or added into boost already. c) Any mistakes I made in my code. ;-) -- Chris Smith <Chris.Smith@xxxxxxxxxxxx> _______________________________________________ alacpp mailing list alacpp@xxxxxxxxxxx http://lists.ellipsis.cx/mailman/listinfo/alacpp