简体   繁体   中英

How to query if any bit in a range is set in a C++ std::bitset?

I am looking for a C++ bitset implementation that can answer if a bit is set in a range. std::bitset , vector , and boost::dynamic_bitset all give access to individual bits that I can loop over, but that isn't the most efficient way to query a range of bits to ask if any bit is set- I don't even need to know which one.

bitset b;
if(b.any(33, 199))
{
    // ...
}

Is there a library that provides this? I would like to run some benchmarks against other implementations (including one I may have to write), but I can't find any that appear to implement this functionality.

Unfortunately in C++11 bitset it is not possible to set a range of bits to the given value by just specifying the boundaries of the range. Iterating over individual bits seems the most we can do. It is also not possible to check if all bits inside the range are set to the same value (1,0).

There is an open source project in Git that provides an alternative implementation of the BitSet ( RangedBitset ) that supports these operations. It uses an array of uint_64t_ words of any size internally, but can also handle ranges specified with the accuracy of the single bit. There you can do the things like

 a.set(4, 8, true); // set the range [ 4 .. 8 [ to true
 bool is_all_range = a.check(2, 6, true); // check if all range is set to 1.

To check if some bit is set in the range [x,y] in bitset, you can use bs._Find_next(x-1) . It returns the next set bit after the position x-1. Then you can check if the returned value is <=y or not.

bool Find_if_bitset_has_any_set_bit_in_range(bitset<M> &bs, int x, int y){
   if(bs._Find_next(x-1)<=y)   return 1;   //TRUE
   return 0;                               //FALSE
}

C++11 的 bitset 提供了你所追求的 any() 方法,但如果这不是一个选项,那么只需使用 b.to_ulong() 并检查非零。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM