Q:

multiple if without else not equivalent to if else? c++

Trying to sort a vector of 0,1,2's in ascending order. I thought the following two are equivalent:
void sortColors(vector<int>& nums) {
    int i=0,j=nums.size()-1;
    int k=0;
    while (k<=j){
        if (nums[k]==0){
            swap(nums[i],nums[k]);
            ++i;
            ++k;
        } 
        else if (nums[k]==1) {
            ++k;
        }
        else if (nums[k]==2){
            swap(nums[j],nums[k]);
            --j;
        }
    }
}

and 
void sortColors(vector<int>& nums) {
    int i=0,j=nums.size()-1;
    int k=0;
    while (k<=j){
        if (nums[k]==0){
            swap(nums[i],nums[k]);
            ++i;
            ++k;
        }
        if (nums[k]==1) ++k;
        if (nums[k]==2){
            swap(nums[j],nums[k]);
            --j;
        }
    }
}

However, only the first is correct. When test running nums={2,0}, the first one does the correct ordering while the second function does nothing. What are the difference here?

A:

No they are not the same, because you change the variable that you use for the condition:
while (k<=j){
    if (nums[k]==0){              
        swap(nums[i],nums[k]);
        ++i;
        ++k;
    }
    if (nums[k]==1) ++k;         // if num[k] == 1
    if (nums[k]==2){             // now k isnt 
                                 // the same as for the last condition
        swap(nums[j],nums[k]);
        --j;
    }
}

while with the if-else version only one of the branches is executed.

