1
std::map<int, int> m;
// initialize m...
//
int n=3;
for (std::map<int, int>::iterator iter = m.begin()+n; iter != m.end(); ++iter)
// Is the above line correct?
{}

Can I increment an iterator by an integer as shown in the code?

Deduplicator
  • 44,692
  • 7
  • 66
  • 118
Taitai
  • 584
  • 2
  • 7
  • 18
  • You can't do that with a map iterator [see this](https://stackoverflow.com/questions/28820047/increment-an-iterator-standard-map). Use std::next – lakeweb Oct 13 '18 at 00:42

2 Answers2

5

You can do "pointer arithmetic" on an iterator only if it is a random access iterator. The iterators of std::set, std::multiset, std::map, and std::multimap are not random access iterators. Supporting the "increment by n" operation efficiently for a map iterator would require some extra bookkeeping within the red-black tree structure, which would add overhead for all users. This is a rarely needed operation, so it isn't supported in the standard library.

You can do it the "slow" way with std::next(m.begin(), n). This simply increments a copy of the iterator n times and returns the result.

Brian Bi
  • 111,498
  • 10
  • 176
  • 312
4

You can use std::advance() or std::next() for this:

std::map<int, int> m;
...
for (auto iter = next(m.begin(), 3); iter != m.end(); ++iter)
{
}

Both std::advance() and std::next() behave optimally regardless of iterator type. If you pass a random-access iterator to them, they will use operator + (). Otherwise, they will repeatedly use operator ++ ().

Sid S
  • 6,037
  • 2
  • 18
  • 24