gpt4 book ai didi

c++ - 不可预测的嵌套循环数量

转载 作者:塔克拉玛干 更新时间:2023-11-02 23:20:33 25 4
gpt4 key购买 nike

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

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

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

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

最佳答案

你需要动态地做:

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,就增加下一个数字。同样, vector 中的每个偏移量代表一个循环变量,在“溢出”时增加下一个偏移量,一旦最重要的偏移量“溢出”,我们就完成了。

高性能变体(使用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;
}

关于c++ - 不可预测的嵌套循环数量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53578307/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com