1
vector<int> v(1, 1);
it = v.begin();

Why *it++ didn't plus one on the first element?

Although I can use *it = *it + 1

I haven't use C++ for years

1

3 Answers 3

4

++ has higher precedence than *.

So first iterator is made to point to next element and then de-referenced using *, you could have collected v[1] on left side.

Use code as below to fix the problem.

#include<iostream>

using namespace std;

int main()
{
vector<int> v(2, 1);
vector<int>::iterator it;
it = v.begin();
(*it)++; //instead of *it++;

cout << v[0] <<  v[1] << endl;
}
Sign up to request clarification or add additional context in comments.

1 Comment

I could not get this code to compile. What am I missing? Here's the code at ideone.com - shar.es/5gmnM
0

Because *it++ means to postincrement it and dereference the result (the original value of it) since the ++ binds tighter (it's equivalent to *(it++)). It does not modify the contents at *it. If you want to increment *it, use (*it)++.

7 Comments

No, it doesn't. It means it++, and dereference the result. The result of a post-increment is the value the iterator had before being incremented. And post-increment on iterators can be inefficient.
what he means is the post increment fires first, and the result that is returned for deref is the prior element. Thus the expensive part.
Yeah, sorry. My mental model of *s++ is that the increment happens after the dereference, but the operator precedence calls it "postincrement then dereference".
@WhozCraig: The potentially expensive part is the copy that postincrement has to make of the original iterator, before it gets advanced. Depending on the iterator type, a copy may be very cheap or quite costly.
@BenVoigt Precisely. The expensive part =) (or maybe... not=P)
|
0

As others have explained

int x = *it++;

is equivalent to

int x = (*it)++;

which is equivalent to

int x = *it;
it = ++it; // prefix  

it is not incremented until after the semicolon (because it is the postfix operator). The posfix ++ operator is usually implemented using the prefix operator like this

template<typename T> vector<T>::iterator vector<typename T>::iterator::operator++(int)
{
   vector<T>::iterator tmp(*this);
   ++(*this); // call prefix operator++()
   return tmp;   
}

where you can see that it returns the value of the iterator before operator++() is done.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.