codest
codest

Reputation: 131

Iterators in c++

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

Upvotes: 1

Views: 171

Answers (3)

Kurt Krueckeberg
Kurt Krueckeberg

Reputation: 1245

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.

Upvotes: 0

user1703205
user1703205

Reputation: 126

++ 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;
}

Upvotes: 4

nneonneo
nneonneo

Reputation: 179422

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

Upvotes: 0

Related Questions