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.
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.
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:
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.
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:
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;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With