Search code examples
c++pointersfor-loopiteratornested-loops

C++ Loop will run at most once


I'm not sure why this loop won't run al the way through. I'm learning c++ and this is also the first time I've used pointers. Any feedback is appreciated. Goal of the program is to take two random numbers 0-200, take the difference, and add it to the vector. Then get the differences of each number and the new number, and so on until there are no more positive possibilities.

#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;
    }
}

Solution

  • You use the same iterator in both nested loops:

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

    When the inner loop is done, it == board.end(), which is also the end condition for the outer loop. Or it would be, if the outer loop wouldn't immediately increment it again - which is undefined behavior! Use different variables. Or use a function.

    Also, your code is unsafe for another reason. This line:

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

    could invalidate all of your iterators - which would make your loops undefined for a different reason.