Creating N nested for-loops

后端 未结 7 1986
终归单人心
终归单人心 2020-12-03 11:16

Is there a way to create for-loops of a form

for(int i = 0; i < 9; ++i) {
    for(int j = 0; j < 9; ++i) {
    //...
        for(int k = 0; k < 9; +         


        
7条回答
  •  既然无缘
    2020-12-03 11:41

    I'm going to take the OP at face value on the example code that was given, and assume what's being asked for is a solution that counts through an arbitrary base-10 number. (I'm basing this on the comment "Ideally I'm trying to figure out a way to loop through seperate elements of a vector of digits to create each possible number".

    This solution has a loop that counts through a vector of digits in base 10, and passes each successive value into a helper function (doThingWithNumber). For testing purposes I had this helper simply print out the number.

    #include 
    
    using namespace std;
    
    void doThingWithNumber(const int* digits, int numDigits)
    {
        int i;
        for (i = numDigits-1; i>=0; i--)
            cout << digits[i];
        cout << endl;
    }
    
    void loopOverAllNumbers(int numDigits)
    {
        int* digits = new int [numDigits];
        int i;
        for (i = 0; i< numDigits; i++) 
            digits[i] = 0;
    
        int maxDigit = 0;
        while (maxDigit < numDigits) {
            doThingWithNumber(digits, numDigits);
            for (i = 0; i < numDigits; i++) {
                digits[i]++;
                if (digits[i] < 10)
                    break;
                digits[i] = 0;
            }
            if (i > maxDigit)
                maxDigit = i;
        }
    }
    
    int main()
    {
        loopOverAllNumbers(3);
        return 0;
    }
    

提交回复
热议问题