首页 > 解决方案 > 不可预知的嵌套循环数

问题描述

我正在尝试制作一个需要嵌套循环才能正常工作的程序。但是嵌套循环的数量取决于用户输入的字符数以及要输出的字符。

到目前为止,这是我的代码。

#include<iostream>
using namespace std;


int main(){
    string str;
    cout<<"Enter some string: ";
    cin>>str;

    // for two characters
    for(int i = 0; i < 2; i++){
        for(int j = 0; j < 2 ; j++){
            cout<<str[i]<<str[j]<<endl;
        }
    };

    // for four characters
    for(int i = 0; i<4; i++){
        for(int j=0;j<4;j++){
            for(int k =0;k<4;k++){
                for(int z=0;z<4;z++)
                    cout<<str[i]<<str[j]<<str[k]<<str[z]<<endl;
                }
        }
    }
    return 0;
}

那么,有什么办法可以解决这个问题。

标签: c++recursion

解决方案


您需要动态执行此操作:

std::vector<unsigned int> offsets(s.size());

bool isContinue;
do
{
    for(auto offset : offsets)
    {
        std::cout << s[offset];
    }
    std::cout << std::endl;

    isContinue = false;
    for(auto offset = offsets.rbegin(); offset != offsets.rend(); ++offset)
    {
        if(++*offset < s.size())
        {
            isContinue = true;
            break;
        }

        *offset = 0;
    }
}
while(isContinue);

背后的想法就像增加数字(十进制):一旦达到 9,就增加下一个数字。同样,向量中的每个偏移量代表一个循环变量,在“溢出”时,增加下一个偏移量,并且一旦最重要的偏移量“溢出”,我们就完成了。

高性能变体(使用goto,保留一个比较和条件变量):

std::vector<unsigned int> offsets(s.size());

NEXT:
for(auto offset : offsets)
{
    std::cout << s[offset];
}
std::cout << std::endl;

for(auto offset = offsets.rbegin(); offset != offsets.rend(); ++offset)
{
    if(++*offset < s.size())
        goto NEXT;

    *offset = 0;
}

推荐阅读