不可预测的嵌套循环数

Sei*_*eld 6 c++ recursion

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

到目前为止这是我的代码.

#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;
}
Run Code Online (Sandbox Code Playgroud)

那么,有没有办法解决这个问题.

Aco*_*gua 6

你需要动态地做:

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);
Run Code Online (Sandbox Code Playgroud)

背后的想法就像向上计数(十进制):一旦达到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;
}
Run Code Online (Sandbox Code Playgroud)