【问题标题】:How to use a set of boost::dynamic_bitsets?如何使用一组 boost::dynamic_bitset?
【发布时间】:2012-12-28 18:52:28
【问题描述】:

我正在尝试使用 dynamic_bitset 对象中的 set,但在运行时遇到断言失败:

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&lt; 工作,它不能假设较短位集中的最高有效位隐式填充为零吗?

有什么方法可以让这组dynamic_bitsets 工作吗?

我也尝试了unordered_set,因为它不需要operator&lt;,但它无法编译,因为dynamic_bitset 没有hash_value,我不知道该怎么写不使用其 to_ulong 成员函数,该函数仅适用于短位集。

【问题讨论】:

    标签: boost set boost-dynamic-bitset


    【解决方案1】:

    断言的原因是operator&lt;的实现方式:

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

    只有第一个操作数的块计数用于遍历位集。 如果第一个 bitset 的大小较大,它将越界访问第二个 bitset。

    您可以使用 std::set 定义和使用自己的比较器,并根据需要处理不同大小的位集的比较:

    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) );
    

    【讨论】:

      猜你喜欢
      • 2013-10-17
      • 1970-01-01
      • 2017-01-14
      • 2015-09-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-02-05
      相关资源
      最近更新 更多