c++lambdafilteriteratorcontainers

How can I create iterators of a filtered vector?


Suppose I have a vector named spot_deals of SpotDeal that is a class:

class SpotDeal
{
public:
    int deal_id_; // primary key, and vector is sorted by id
    string ccy_pair_; // ccy pair, e.g. GBPUSD, AUDUSD
    double amount_;
}

Say I need to pass two subset of spot_deals to a function foo for some computation. I could make copies, however, that would cost memory and time. Actually foo only needs iterators of deals. So can I make 2 iterators of vector<SpotDeal>, namely it1 and it2 and pass them to foo?

The two subset of spot_deals could be filtered by ccy_pair_, e.g. deals of GBPUSD and AUDUSD, or by other conditions. So I'm looking for a way to define an iterator defined by a vector and a lambda function (could equivalently be a functor though).

Is there a way to write a helper function make_filtered_iterator so that I can have something like below?

auto it1 = make_filtered_iterator(spot_deals, filter_lambda1);
auto it2 = make_filtered_iterator(spot_deals, filter_lambda2);
foo(it1, it2);

Solution

  • The answer is certainly "yes." C++ iterators in the STL style can be made to do all sorts of tricks. A common but basic one is making an iterator for std::map which when dereferenced gives only the key or the value.

    In your particular case, a simple implementation might be like this:

    template <typename BaseIterator>
    struct filtered_iterator : BaseIterator
    {
        typedef std::function<bool (const value_type&)> filter_type;
    
        filtered_iterator() = default;
        filtered_iterator(filter_type filter, BaseIterator base, BaseIterator end = {})
            : BaseIterator(base), _end(end), _filter(filter) {
            while (*this != _end && !_filter(**this)) {
                ++*this;
            }
        }
    
        filtered_iterator& operator++() {
            do {
                BaseIterator::operator++();
            } while (*this != _end && !_filter(**this));
            return *this;
        }
    
        filtered_iterator operator++(int) {
            filtered_iterator copy = *this;
            ++*this;
            return copy;
        }
    
    private:
        BaseIterator _end;
        filter_type _filter;
    };
    
    template <typename BaseIterator>
    filtered_iterator<BaseIterator> make_filtered_iterator(
            typename filtered_iterator<BaseIterator>::filter_type filter,
            BaseIterator base, BaseIterator end = {}) {
        return {filter, base, end};
    }
    

    I set a default value for end because typically you can use a default-constructed iterator for that. But in some cases you might want to filter only a subset of the container, in which case specifying the end makes it easy.