优化二进制递增循环 [英] optimize binary increment loop
本文介绍了优化二进制递增循环的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
今天早些时候,我提出了一个问题,关于获得每一个可能的组合,我被给了一个好的提示使用二进制循环,经过一些想法,我想出了下面的代码在C + +:
Earlier today I asked a question regarding getting every possible combinations and I was given a good hint on using a binary loop, after some thoughts into it I came up with the following code in C++:
vector<bool>binary(size,0);
bool filled=false;
while(filled==false)
{
bool setdigit=true;
for(int k=0;k<size;k++)
{
if(setdigit==true)
{
if(binary[k]==false)
{
binary[k]=true;
setdigit=false;
}
else //when the digit is already true
{
binary[k]=false;
}
}
}
for(int i=0;i<size;i++)
{
if(binary[i]==false)
{
filled=false;
break;
}
else filled=true;
}
}
代码似乎工作,但是测试是否二进制递增完成编码非常差,我应该如何改善退出条件,甚至循环过程?
The code seems to work but the way to test whether the binary increment is finished is very badly coded, how should i go to improve the exit condition or even the looping process?
推荐答案
伪代码:
for (i=0;i<2^size;i++)
binary = std::bitset(i); /* the bits of i are the bits you are looking for */
这篇关于优化二进制递增循环的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文