Consider a vector in which the contents are "xxx" and the code:
1 2 3 4 5 6 7 8
|
for (int g=0; g<Code.size(); g++) {
if (Code[g]==Code[i]) {
if (g==i) {
}
else if (g>i){
Code.erase(Code.begin()+g);
}
}
| |
given that
i is 0, the
if(g==i)
body is entered the first iteration of the loop and nothing changes. The vector's content is still: "xxx"
Next, the value of g is incremented and then evaluated (
g<Code.size()
) to determine if the loop should iterate again. Since 1 is less than 3, it should iterate again.
So, now
g is 1 and the
else if (g>i)
body is entered and the 2nd element (that with index 1) is erased from the vector. The vector's content has been changed. It is now "xx".
Next, the value of
g is incremented and then evaluated (
g<Code.size()
) to determine if the loop should iterate again. Since 2 is not less than 2 (the new size of the vector) the loop will not iterate again, leaving you with the contents "xx"
The basic problem is that when you erase an element of a vector, every element to the right of that element is moved one slot to to the left. Thus, the element you just erased at index
g becomes another element, but you always increment
g without checking what the new element at the index you just erased was.
tldr: A while loop would be more appropriate as you don't want to increment the index every iteration of the loop.
1 2 3 4 5 6 7 8
|
unsigned g = i+1 ;
while ( g < Code.size() )
{
if ( Code[g] == Code[i] )
Code.erase(Code.begin()+g) ;
else
++g ;
}
| |