There are a few options. Because a map iterator is only a bidirectional iterator (as opposed to a random-access iterator), you cannot simply write it + 4
to advance the iterator by four as you can with a random-access iterator.
I guess the first option is to use std::advance
to get the iterator range that you want. As so:
std::map<int, Class>::iterator it = list.begin();
std::advance(it, 2); // move to index 2
std::map<int, Class>::iterator it_end = it;
std::advance(it_end, 2); // move to index 4
for(; it != it_end; ++it)
{
cout << it->first << " " << it->second.GetPrice() << endl;
}
One of the problems with the above is that you are kind of doing the traversal (std::advance
) before doing the traversal (for-loop), which is inefficient.
Another solution is to simply keep a separate count of the index. As so:
std::size_t index = 2;
std::map<int, Class>::iterator it = list.begin();
std::advance(it, index); // move to index 2
for(; (it != list.end()) && (index < 4) ; ++it, ++index) // inc. index, stop at index 4
{
cout << it->first << " " << it->second.GetPrice() << endl;
}
I think that this solution is better in general, and doesn't cost much at all.