How can I stop repeating "n" to the end of the map when iterators are not random access?

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

for (it=final.begin(); it!=final.end()-window; it++)
+3
source share
4 answers

You cannot subtract cards directly from the iterator, because this is an expensive operation (in practice, it does --iter the required number of times). If you really want to do this, you can use the standard forward library function.

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

.

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

T1 T2 .

+3

:

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
}

:

  • , window.
  • processCount , (, )
  • STL, size() O (n) , O (1). , size() , .
  • 'end ()', on the other hand, has an amortized constant time, so it must be OK to be in a for-loop state
  • ++itmaybe faster than it++. The post-increment statement creates a temporary object, while the other does not. When a variable is a simple integral type, the compiler can optimize it, but with iterators this is not always the case.
0
source

Source: https://habr.com/ru/post/1795026/


All Articles