Every now and then I need to iterate over a subset of the elements of a container or just want to extract them and neglect the rest. I end up using boost::range::adaptors::filtered
to create this lazy collections.
for(auto&& i : container | filtered(predicate)) {
// .. do stuff
}
Is there a reason for the lack of a collect algorithm (as in Ruby's collect) in the STL (we only have copy_if which is not the same)? Or any reason against using it?
A possible implementation could be:
template<class Container, class Predicate>
Container collect(Container&& c, Predicate&& p) {
Container n;
for(auto&& i : c) {
if(p(i)) {
n.push_back(i);
}
}
return n;
}
but a lazy_collect
might also be useful to avoid copying.
All answers below are great. I wish I could mark all of them. I didn't knew about std::back_inserter
. Collecting stuff is now as easy as:
boost::copy( orig | filtered(predicate), std::back_inserter(collection));