2012-04-28 55 views
2

我有一個給定長度的C++位集。我想生成這個bitset的所有可能的組合,爲此我想添加1 2^bitset.length時間。這個怎麼做? Boost庫解決方案也可以接受加1到C++位集

+1

嗯......我不能看到一個添加操作並手動檢查所有位似乎不可行。所以我還沒有嘗試過任何東西 – wirate 2012-04-28 11:21:27

回答

2

所有可能的組合?只需使用64位無符號整數,讓您的生活更輕鬆。

+0

然後,我將不得不將這個整數轉換爲bitset一次又一次地檢索個別位的值。由於位集<一些可變大小>在STL位集中是不可能的,因此我將使用boost。如果我讓bitset < value > mybitset,和值= 2,我將需要00010而不是10.這可能嗎?希望它對您有意義:) – wirate 2012-04-28 11:34:18

+1

不,您不必將其轉換回bitset以檢索單個位 - 學習如何使用按位運算符。 00010與10相同;它只取決於你想要提取的整數的前導零。 – zvrba 2012-04-28 11:37:22

+0

你的意思是我可以看看如果第三位的int是否設置?請指點我的地方! – wirate 2012-04-28 11:39:41

5

試試這個:

/* 
* This function adds 1 to the bitset. 
* 
* Since the bitset does not natively support addition we do it manually. 
* If XOR a bit with 1 leaves it as one then we did not overflow so we can break out 
* otherwise the bit is zero meaning it was previously one which means we have a bit 
* overflow which must be added 1 to the next bit etc. 
*/ 
void increment(boost::dynamic_bitset<>& bitset) 
{ 
    for(int loop = 0;loop < bitset.count(); ++loop) 
    { 
     if ((bitset[loop] ^= 0x1) == 0x1) 
     { break; 
     } 
    } 
} 
+0

+1 v.useful - ty – kfmfe04 2013-03-19 08:59:19

0

使用boost庫,你可以嘗試以下方法:

例如,長度的位集4

boost::dynamic_bitset<> bitset; 
for (int i = 0; i < pow(2.0, 4); i++) { 
    bitset = boost::dynamic_bitset<>(4, i); 

    std::cout << bitset << std::endl; 

}