Question: I would like to traverse a map in C++ with iterators but not all the way to the end.
The problem is that even if we can do basic operations with iterators, we cannot add or compare iterators with integers.
How can I write the following instructions? (`final` is a map; `window`, an integer)

```
for (it=final.begin(); it!=final.end()-window; it++)

```

Answer: 
You cannot subtract from a map iterator directly, because it is an expensive operation (in practice doing --iter the required number of times). If you really want to do it anyway, you can use the standard library function 'advance'. 

```
map<...>::iterator end = final.end();
std::advance(end, -window);

```

That will give you the end of your window.
Another solution:

```
size_t count=final.size();
size_t processCount=(window<count?count-window:0);
for (it=final.begin(); processCount && it!=final.end(); ++it, --processCount)
{
  // loop body
}

```

This one is a bit safer:

* It takes care of the case when your map is actually smaller than the value of `window`.
* It will process at most `processCount` elements, even if you change the size of your map inside your loop (e.g. add new elements)
* According to STL, `size()` can take O(n) time to compute, although usual implementations can do this in O(1). To be on the safe side, it is better not to call size() many times, if it is not necessary.
* 'end()' on the other hand has amortized constant time, so it should be OK to have it in the for-loop condition
* `++it` may be faster than `it++`. The post-increment operator creates a temporary object, while the other - does not. When the variable is a simple integral type, compiler can optimise it out, but with iterators it is not always the case.