C++ Loop 最多 运行 一次

C++ Loop will run at most once

我不确定为什么这个循环不会 运行 一直结束。我正在学习 C++,这也是我第一次使用指针。任何反馈表示赞赏。该程序的目标是取两个随机数 0-200,取差,并将其添加到向量中。然后得到每个数和新数的差,以此类推,直到没有更多的正数可能。

#include<iostream>
#include<stdlib.h>
#include<time.h>
#include<vector>
#include<algorithm>

int main(int argc, const char * argv[]) {
    using namespace std;
    int m,n; //Two random numbers between 1 and 200
    vector<int> board;
    vector<int>::iterator it;

    srand(time(NULL));

    m = rand() % 201;
    n = rand() % 201;

    board.insert(board.begin(), m);
    board.insert(board.begin(), n);

    cout << "\nThe two numbers are " << m << " and " << n << endl;


    for(it=board.begin(); it != board.end(); it++){
        for(vector<int>::iterator j = board.begin(); j != board.end(); j++){
            int a = *j - *it;
            if (a > 0) { //Is non-negative
                if (find(board.begin(), board.end(), a) != board.end()) {
                    board.insert(board.end(), a);
                }
            }
        }

        for (it=board.begin(); it<board.end(); it++) {
            cout << ' ' << *it;
            cout << ' ';
        }
        return 0;
    }
}

您在两个嵌套循环中使用了相同的迭代器:

for(it=board.begin(); it != board.end(); it++){
    // ... 
    for(it=board.begin(); it != board.end(); it++){
        // ...
    }
}

当内循环完成后,it == board.end(),这也是外循环的结束条件。或者,如果外层循环不会立即再次递增它——这是未定义的行为!使用不同的变量。或者使用函数。

此外,您的代码不安全还有其他原因。这一行:

board.insert(board.end(), a);

可能会使您的所有迭代器失效 - 这会使您的循环因其他原因而未定义。