2012-12-28 41 views
1

我試圖使用dynamic_bitsetset一個對象,但我在運行時得到一個斷言失敗:如何使用一組boost :: dynamic_bitsets?

a.out: boost/dynamic_bitset/dynamic_bitset.hpp:1291: 
bool boost::operator<(const boost::dynamic_bitset<Block, Allocator>&, 
         const boost::dynamic_bitset<Block, Allocator>&) 
[with Block = long unsigned int, 
     Allocator = std::allocator<long unsigned int>]: 
Assertion `a.size() == b.size()' failed. 

下面是代碼:

#include <iostream> 
#include <set> 
#include <boost/dynamic_bitset.hpp> 

int main() { 
    typedef boost::dynamic_bitset<> bitset; 
    std::set<bitset> myset; 
    bitset x(2, 0); 
    bitset y(3, 1); 
    myset.insert(x); 
    myset.insert(y); 
    return 0; 
} 

我想知道爲什麼插入的dynamic_bitset對象的大小必須相同。爲了使operator<正常工作,難道它不能假定較短比特中的最高有效位被隱式填充爲零嗎?

有什麼辦法可以讓dynamic_bitset的工作集合起來嗎?

我也嘗試了unordered_set,因爲它不需要operator<但它不能編譯,因爲dynamic_bitset沒有hash_value,我不知道該怎麼寫,而不使用其to_ulong成員函數,這隻適用於短的位集。

回答

4

的原因說法是operator<執行的方式:只有第一個操作數的塊數被用於通過位集迭代

for (size_type ii = a.num_blocks(); ii > 0; --ii) 

。 如果第一個bitset的大小更大,它將訪問第二個bitset越界。

您可以定義和使用的std ::設置使用自己的comperator和處理不同尺寸的位集的比較,你認爲合適:

struct my_less { 
    bool operator()(const boost::dynamic_bitset<>& lhs, 
        const boost::dynamic_bitset<>& rhs) const 
    { 
     //TODO: implement custom comparison for lhs < rhs 
     return false; 
    } 
}; 
typedef boost::dynamic_bitset<> bitset; 
std::set<bitset,my_less> myset; 

myset.insert(bitset(2, 0)); 
myset.insert(bitset(3, 1)); 
相關問題