(just a logic flaw)
1 2 3 4 5
|
for(i=0;i<v.size();i++)
{
v[i] = i++;
cout << "element of vector is\t"<<v[i]<<endl;
}
|
When you enter the loop i = 0;
@ line 3 this happens:
First a copy of i is made (0). internally i is then incremented to 1. The copy is what is returned from the operator (0), 0 is then assigned to the index of i which is 0, this takes place before the operator++. At line 4, i now takes the value of the ++ operator modification of 1, I'm guessing you created this vector and put 0's in for the values, because at position [1] the vector holds a zero value.
Now next iteration, you've already incremented i inside the loop, the for control increments, i is now 2. @ line 3 same thing as above, vector index 2 assigns the value 2 from the ++ operator, on the following line i is now 3, you print out vector @ index 3, which is zero.
You loop only prints 5 because your control variable is incremented twice for each pass.
Postfix ++ operator works like this.
1 2 3 4 5 6
|
int operator++(int)
{
int temp = *this; //Copy made
++*this;
return temp;
}
|
Prefix works like this
1 2 3 4
|
int operator++()
{
return *this+=1; //the actual variable is returned as a copy.
}
|
Should't i++ behave the same way as i+1? Kindly help :) |
i + 1 creates a temporary variable of type int that is the sum of i and 1, as ne555 has already stated, this does not modify i.