c++ - 不可预知的嵌套循环数
问题描述
我正在尝试制作一个需要嵌套循环才能正常工作的程序。但是嵌套循环的数量取决于用户输入的字符数以及要输出的字符。
到目前为止,这是我的代码。
#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,就增加下一个数字。同样,向量中的每个偏移量代表一个循环变量,在“溢出”时,增加下一个偏移量,并且一旦最重要的偏移量“溢出”,我们就完成了。
高性能变体(使用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;
}
推荐阅读
- python-3.x - 在 Django Rest Framework 中订购?
- python - 与 Instagram 上的评论互动的问题
- javascript - 带有实时流嵌入的 iframe 音频无法正常工作(缩放)
- oracle - 两个列表之间的 IN 运算符在 oracle 中不起作用
- android - 条纹临时密钥
- python - 如何使用 ImageDataGenerator 进行固定转换?
- r - 从 R 中的 NCBI 中提取元数据的问题
- svg - 尾随的目的是什么
SVG 末尾的标签? - sql - SQL查询查找表的每一列中非空值的计数?
- reactjs - 使用 Axios 身份验证的反应路由器