How to Increment an Iterator by 2

Can I increment an iterator by just adding a number?

It works if the iterator is a random access iterator, which vector's iterators are (see reference). The STL function std::advance can be used to advance a generic iterator, but since it doesn't return the iterator, I tend use + if available because it looks cleaner.

C++11 note

Now there is std::next and std::prev, which do return the iterator, so if you are working in template land you can use them to advance a generic iterator and still have clean code.

can I increment an iterator by an integer?

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.

how to use two or more iterators to increment inside a for loop

A for loop has the following syntax:

for ( expression ; expression ; expression )

There are 3 expressions separated by semicolons. You have 6 expressions separated by semicolons. That's invalid syntax.

You should write it as follows:

for(i=0,j=10; j>=0 && i<10; i++,j--)

For the first expression, separate the two assignments with the comma operator. Similarly for the third expression. For the second, you want both conditionals to be true, so separate them with the logical AND operator &&.

Also, the error you got was not while executing but while compiling.

Incrementing using iterator

Change it to:

for(iter =scores.begin(); iter !=scores.end(); iter++)
{
(*iter)++;
}

In C++ operators have different precedences, see here for a table.

Postfix increment is performed before the de-reference.

What happens if you increment an iterator that is equal to the end iterator of an STL container

Following is the quote from Nicolai Josuttis book:

Note that advance() does not check
whether it crosses the end() of a
sequence (it can't check because
iterators in general do not know the
containers on which they operate).
Thus, calling this function might
result in undefined behavior because
calling operator ++ for the end of a
sequence is not defined

In other words, the responsibility of maintaining the iterator within the range lies totally with the caller.

Is it allowed to increment an end iterator?

No the behaviour is undefined. You are allowed to set an iterator to end(), but you must not increment it or dereference it.

You are allowed to decrement it so long as the backing container is not empty.



Related Topics



Leave a reply



Submit