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
++ 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;
}
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)++.
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.*s++ is that the increment happens after the dereference, but the operator precedence calls it "postincrement then dereference".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.