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?
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?
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.
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 ++ ()
.