为什么我的代码在 '++' 运算符之后会出现 i++ 和 numsWon++ 混乱?

Why does my code mess up with i++ and numsWon++ when the '++' operators are after?

我在 LeetCode 上遇到了第 1535 题(找到数组游戏的赢家)。我决定使用顶级解决方案,它看起来像这样:

int getWinner(vector<int>& A, int k) {
    int cur = A[0], win = 0;
    for (int i = 1; i < A.size(); ++i) {
        if (A[i] > cur) {
            cur = A[i];
            win = 0;
        }
        if (++win == k) break;
    }
    return cur;
}

然而,我是这样实现的:

class Solution {
public:
    int getWinner(vector<int>& arr, int k) {
        int win = arr[0];
        int numsWon = 0;
        
        for(int i = 1; i < arr.size(); i++) {
            if(arr[i] > win) {
                numsWon = 0;
                win = arr[i];
            }
            
            if(numsWon++ == k) break;
        }
        return win;
    }
};

在我切换 ++ 运算符之前,代码无法运行。有谁知道为什么?

用于:

if (++win == k) break;    

win的值先加1,然后通过比较运算符。和做的一样。

win = win + 1;  
if(win == k) break;  

当 ++ 在 win 之后时,它会在比较后递增 win 的值,例如:

if(win == k){  
    win = win + 1;
    break;
}

++x 发生在赋值之前 (pre-increment),但 x++ 发生在赋值之后 (post-increment)。 x++ 执行语句,然后增加值。 ++x 增加值然后执行语句。

阅读有关 post 和 C++ 中的预递增。

Post and Pre increment gfg

What is the difference between pre-increment and post-increment in the cycle (for/while)?