Question

how would one implement generic (aka works for multimap, sorted vector ...) equal range iterator? By this I mean it is an iterator that is a pair of iterators (begin and end of a particular equal_range)

Motivation for this is that I have a multimap that is called sortedword2word , and I use it to detect anagrams in an array of strings. So I would like to have a way to iterate over each equal range easily (easily as in LOC/readability way - I know I can easily do it by manually checking for .end() and if next is the same as current...)

If boost has implemented functionality like this that is acceptable A also.

Was it helpful?

Solution

Maybe like this:

template <typename Iter> class eqrange
{
    Iter a, b, e;

    void adv()
    {
        e = a;
        while (e != b && *e == *a) { ++e; }
    }

public:

    eqrange(Iter x, y) : a(x), b(y) { adv(); }

    Iter begin() { return a; }
    Iter end()  { return e; }

    eqrange & operator++() { b = e; adv(); }

    bool operator==(eqrange const & rhs) const
    {
        return a == rhs.a && b == rhs.b && e == rhs.e;
    }

    eqrange make_end() const
    { 
        return eqrange(b, b);
    }
};

template <typename Iter>
eqrange<Iter> er(Iter b, Iter e)
{
    return eqrange<Iter>(b, e);
}

Usage:

auto r = er(v.begin(), v.end()), e = r.make_end();

while (r != e)
{
    for (auto x : r) { /* ... */ }
    ++r;
}

OTHER TIPS

Writing custom iterators can be a pain (if you're going to be rigorous in terms of meeting all the requirements of, say, the ForwardIterator concept).

Will the following suffice?

template <typename Range, typename Func>
void foreach_equal_range(Range& range, Func func)
{
    using std::begin;
    using std::end;
    foreach_equal_range(begin(range), end(range), func);
}

template <typename ForwardIt, typename Func>
void foreach_equal_range(ForwardIt begin, ForwardIt end, Func func)
{
     while (begin != end)
     {
         auto it = std::upper_bound(begin, end, *begin);
         func(begin, it);
         begin = it;
     }
}

i would do something like this (hopefully i understood the question in detail..) :

template<typename Container, typename Function>
void                  apply(Container& a, const Container& b, Function f)
{
  auto                aItr = a.begin();
  auto                bItr = b.begin();

  for (; aItr != a.end() && bItr != b.end(); ++aItr, ++bItr)
    f(*aItr, *bItr);
}

Assuming you can use C++11, but it is still easilly modifiable to match older C++ norms.

jav

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top