I'm not sure C++ provides you much help here: you just have to implement an iterator.
Keep in mind that an iterator is just a class with particular members. An iterator is a class with operator *
, ->
, ==
, !=
, and ++
, and maybe a few more if you can go back and/or do random seeks.
Internally, your iterator would hold the two iterators into your map, a map<int, map<int, Stuff>>::iterator
(the "outer" iterator) and map<int, Stuff>::iterator
(the "inner" iterator).
++
would attempt to increment the inner iterator, and if that fails, increment the outer iterator, and start the inner iterator at the map the outer iterator is pointing too. Something like:
iterator &operator ++ () {
++m_inner;
// if we've reached the end of the inner iterator,
// find the next non-empty map, and start iterating through it.
// Stop if we read the end of the outer map.
// (we're pointing to end() of the whole thing._
while(m_inner == m_outer->end() && m_outer != m_outer_end) {
++m_outer;
m_inner = m_outer->begin();
}
}
(The loop is for skipping empty maps. Note that you'll need a similar loop in your begin
implementation.)
On your main class, you also need implementations of begin
, end
(both const and non-const).
The other operators are hopefully trivial once you understand that iterators are just normal objects.
Hopefully, you can see why this might be a bit of code to deal with: you might consider some of the comments suggestions about using the other map type (map<pair<int, int>, Stuff>
) which would let you just typedef map<pair<int, int>, Stuff>::iterator iterator
.