Q:

Return an iterator range (subset of a main list)

I would like to code a method capable of returning a range of iterators to represent a subset of a bigger list.
Can such "subset" not have being made of contiguous objects ?
For example, if I have a std::list with n objects.
eg.
| object1 | object2 | object3 | object4 | ... | objectn

Can I return a range of iterators (a pair of begin / end we can call ItBegin and ItEnd) which would include only Object 1,3 and 4 ?
eg.
| object1 | object2 | object3 | object4 | ... | objectN
     ^                   ^         ^                      ^
     |                   |         |                      |
   ItBegin           ++ItBegin ++ItBegin                ItEnd

Is that possible or do I need to copy the objects (or use pointers to avoid the copy) onto a new list and return that list ?
Please note that the iterator(s) subset would just be used for reading. (a pair of const_iterator would do the job)
Thanks!
Giacomo

A:

If you don't mind using Boost, you could use filter_iterator, e.g.
struct ShouldIncludeChecker
{
    bool operator()(const Object& obj) const
    {
       return obj == object1 || obj == object3 || obj == object4;
       // ^ Customize this to fit your need.
    }
};

typedef boost::filter_iterator<ShouldIncludeChecker, std::list<Object>::iterator>
        filter_iterator;

ShouldIncludeChecker checker;
std::list<Object>::iterator old_begin = the_list.begin();
std::list<Object>::iterator old_end = the_list.end();
filter_iterator new_begin (checker, old_begin, old_end);
filter_iterator new_end (checker, old_end, old_end);

for (filter_iterator it = new_begin; it != new_end; ++ it)
{
   // read *it
}

Also, if the thing you are reading to can be made into an output iterator, you could just use std::remove_copy_if.

