Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to implement equal range "iterator"

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.

like image 522
NoSenseEtAl Avatar asked Jun 27 '13 09:06

NoSenseEtAl


People also ask

How do you implement an iterator in Java?

To implement an Iterator, we need a cursor or pointer to keep track of which element we currently are on. Depending on the underlying data structure, we can progress from one element to another. This is done in the next () method which returns the current element and the cursor advances to next element.

What is the use of begin () and end () methods of iterators?

The end () method returns a pointer pointing to the element that comes after the last element of the container. This element is not real, it is a virtual element that contains the address of the last element. The following program illustrates the begin () and end () operations of iterators:

Can iterator be implemented as an inner class?

Note: The Iterator class can also, be implemented as an inner class of the Data Structure class since it won’t be used elsewhere. How next () and hasNext () work? To implement an Iterator, we need a cursor or pointer to keep track of which element we currently are on.

How do you know if two iterators are equal?

Two iterators are said to be equal if both of them are pointing towards the same location. Otherwise, they are considered unequal. In the expression shown below, consider it1 and it2 as two random-access iterators:


Video Answer


1 Answers

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;
}
like image 157
Kerrek SB Avatar answered Sep 29 '22 05:09

Kerrek SB