【问题标题】:C++ Loop will run at most onceC++ 循环最多运行一次
【发布时间】:2015-01-27 02:54:30
【问题描述】:

我不确定为什么这个循环不会一直运行。我正在学习 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;
    }
}

【问题讨论】:

    标签: c++ pointers for-loop iterator nested-loops


    【解决方案1】:

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

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

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

    另外,您的代码不安全还有一个原因。这一行:

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

    可能会使您的所有迭代器无效 - 这会使您的循环因不同的原因而未定义。

    【讨论】:

    • 内部for循环使用迭代器“j”。
    • @user3591541 有两个内部循环。一个使用j,另一个使用it。也许您没有按照您的预期编写大括号?
    • 就是这样。谢谢!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-17
    • 2018-05-02
    • 2014-12-18
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多