Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I stop iterating "n" before the end of a map when the iterators aren't random-access?

Tags:

c++

iterator

map

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++)
like image 580
user636287 Avatar asked Jan 21 '23 09:01

user636287


2 Answers

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.

like image 156
Bo Persson Avatar answered Feb 07 '23 12:02

Bo Persson


std::map<T1, T2>::iterator it = final.begin();
for (int i = 0; i < final.size()-window; ++i, ++it)
{
  // TODO: add your normal loop body
}

Replace T1 and T2 with the actual types of the keys and values of the map.

like image 22
Oswald Avatar answered Feb 07 '23 12:02

Oswald