Класс C ++ boost :: dynamic_bitset с примерами

Опубликовано: 7 Января, 2022

В бусте более 150 библиотек, из которых пара наиболее часто используемых библиотек уже включена в стандартную библиотеку C ++. Dynamic_bitset - это мощная библиотека, используемая для обработки битов. Класс dynamic_bitset используется для представления набора битов в форме 0 (сброс) или 1 (набор). dynamic_bitset является улучшением по сравнению с набором битов (std :: bitset и boost :: bitset ), который выделяет любую требуемую длину бит во время выполнения, в отличие от набора бит, длина которого должна быть определена во время компиляции.

Параметр dynamic_bitset, если он находится в заголовке boost, boost / dynamic_bitset.hpp .

Синтаксис:

 boost :: dynamic_bitset <uint8_t> B (N, число);

Параметры конструкторов:

  • N, что означает необходимое количество бит в наборе.
  • num означает любое целое значение, биты которого будут сохранены.
  • uint8_t обозначает размер блока (здесь 8, он также может быть пустым, если нам не нужно указывать размер блока).

Доступ к каждому индивидуальному биту dynamic_bitset можно получить аналогично оператору индексации битового набора [].

Обратите внимание, что битовое представление числа B в dynamic_bitset длины n представлено как:

 B [n-1] B [n-2] ... B [1] B [0]

Другими словами, индексация в dynamic_bitset работает в обратном порядке (аналогично битовому набору). Каждый бит в dynamic_bitset занимает ровно 1-битное пространство из-за его оптимизации, что делает операции быстрее, чем логический вектор.

Функции-члены:
Основные функции-члены, которые могут выполняться для dynamic_bitset, перечислены ниже:

  • set () : присваивает каждому биту 1
  • reset () : он присваивает n- му биту 0, если n передается в аргументе, иначе он очищает весь объект битового набора.
  • flip () : инвертирует любой заданный бит, т.е. переключает 0 на 1 или наоборот.
  • size () : возвращает размер объекта dynamic_bitset
  • resize () : используется для увеличения или уменьшения размера объекта.
  • push_back () : увеличивает размер объекта dynamic_bitset на единицу и помещает значение в MSB
  • pop_back () : удаляет один бит из MSB
  • num_blocks () : возвращает количество блоков в битовом наборе
  • append : добавляет биты в самый старший бит. Это увеличивает размер битового набора на bits_per_block. Для i в диапазоне [0, bits_per_block) бит в позиции (size + i) устанавливается в ((value >> i) & 1)
  • empty () : возвращает true, если длина dynamic_bitset равна 0, иначе возвращает false.
  • count () : возвращает количество установленных битов в dynamic_bitset.
  • all () : он проверяет, все ли биты в dynamic_bitset установлены, если они установлены, возвращает true, иначе false.
  • any () : он проверяет, установлен ли хотя бы один из битов в dynamic_bitset, если они установлены, он возвращает true, иначе false.
  • none () : он проверяет, не установлен ли ни один из битов в dynamic_bitset, если ни один из них не установлен, он возвращает true, иначе false.
  • test () : проверяет, установлен ли i- й бит. Если установлено, возвращается истина, иначе ложь.

Example 1:

#include <boost/dynamic_bitset.hpp>
#include <iostream>
  
using namespace std;
  
int main(int argc, char* argv[])
{
    int bit_size = 8;
  
    // B1 is initialized with size 0
    // with all bits 0
    boost::dynamic_bitset<> B1;
  
    // B2 is initialized with size
    // bit_size with all bits 0
    boost::dynamic_bitset<> B2(bit_size);
  
    // B3 is initialized with size
    // bit_size and value 14
    boost::dynamic_bitset<> B3(bit_size, 14);
  
    // B4 is initialized with size
    // bit_size, value 14 and
    // block_size of 8 bits
    boost::dynamic_bitset<uint8_t> B4(16, 84);
  
    // Empty
    cout << "Content of B1 is: "
         << B1 << endl;
  
    // 00000000
    cout << "Content of B2 is: "
         << B2 << endl;
    cout << "Binary representation of 14 in 8 bit: "
         << B3 << endl;
    cout << "Content of B4 is: "
         << B4 << endl
         << endl;
  
    // Setting 1 st of B2 to 1
    cout << "Content of B2 before set(): "
         << B2 << endl;
  
    B2.set(0);
    cout << "Content of B2 after set(0): "
         << B2 << endl;
  
    // Setting every bits of B22 to 1
    B2.set();
    cout << "Content of B2 after set(): "
         << B2 << endl;
  
    // Resetting 2nd bit to 0
    B2.reset(1);
    cout << "After resetting 2nd bit of B2: "
         << B2<< endl;
  
    // Resetting every bit to 0
    B2.reset();
    cout << "After resetting every bit of B2: "
         << B2 << endl;
  
    // Flipping first bit of B3
    cout << "Content of B3 before flip(): "
         << B3 << endl;
  
    B3.flip(0);
    cout << "Content of B3 after flip(0): "
         << B3 << endl;
  
    // Flipping every bits of B3
    B3.flip();
    cout << "Content of B3 after flip():  "
         << B3 << endl
         << endl;
  
    // Size of B1, B2, B3, B4
    cout << "Size of B1 is: "
         << B1.size() << endl;
    cout << "Size of B2 is: "
         << B2.size() << endl;
    cout << "Size of B3 is: "
         << B3.size() << endl;
    cout << "Size of B4 is: "
         << B4.size() << endl
         << endl;
  
    // Resizing B1 to size 4,
    // default bit-value 0
    B1.resize(4);
    cout << "B1 after increasing size to 4 bits: "
         << B1 << endl;
  
    // Resizing B1 to size 8, bit-value 1.
    // If num_bits > size() then the bits
    // in the range [0, size()) remain the same,
    // and the bits in [size(), num_bits)
    // are all set to value (here 1).
    B1.resize(8, 1);
    cout << "B1 after increasing size to 8 bits: "
         << B1 << endl;
  
    // Resizing B1 to size 1 i.e.
    // slicing [1, B1.size()-1)
    B1.resize(1);
    cout << "B1 after decreasing size to 1 bit:  "
         << B1 << endl
         << endl;
  
    // Pushing a set bit at MSB in B1
    B1.push_back(1);
    cout << "B1 after push(1) operation:   "
         << B1 << endl;
  
    // Pushing a reset bit at MSB in B1
    B1.push_back(0);
    cout << "B1 after push(0) operation : "
         << B1 << endl
         << endl;
  
    // Poping 1 bit from MSB in B1
    cout << "B1 before pop operation: "
         << B1 << endl;
  
    B1.pop_back();
    cout << "B1 after pop operation:   "
         << B1 << endl
         << endl;
  
    // Number of blocks = number of bits / block size
    cout << "Number of blocks in B4: "
         << B4.num_blocks() << endl
         << endl;
  
    // Checking if any bitset is empty
    cout << "B1 is "
         << (B1.empty() ? "empty" : "not empty")
         << endl;
    cout << "B2 is "
         << (B2.empty() ? "empty" : "not empty")
         << endl;
  
    // Resizing B3 to 0
    B3.resize(0);
    cout << "B3 is "
         << (B3.empty() ? "empty" : "not empty")
         << endl
         << endl;
  
    // Counting number of set bits in B4
    cout << "Content of B4 is: " << B4 << endl;
    cout << "Number of set bits in it are: "
         << B4.count() << endl
         << endl;
  
    // Checking if all of the bits of B2 is set
    B2.set(); // B2 => 11111111
  
    cout << "All bits in B2 are "
         << (B2.all() ? "set" : "not set") << endl;
  
    B2.reset(2); // B2 => 11111011
    cout << "All bits in B2 are "
         << (B2.all() ? "set" : "not set")
         << endl
         << endl;
  
    // Checking if any of the bits of B2 is set
    cout << (B2.any() ? "Atleast one" : "No")
         << " bit in B2 is set " << endl;
    B2.reset(); // B2 => 00000000
  
    cout << (B2.any() ? "Atleast one" : "No")
         << " bit in B2 is set " << endl
         << endl;
  
    // Checking if none of the bits of B2 are set
    // B2 => 00000000
    if (B2.none())
        cout << "None of the bits in B2 is set";
    else
        cout << "Atleast one bit in B2 is set";
    cout << endl
         << endl;
  
    // Testing if 1st bit of B1 is set or not
    cout << "Content of B1 is: " << B1 << endl;
    if (B1.test(1))
        cout << "B1[1] is set";
    else
        cout << "B1[1] is reset";
    return 0;
}
Output:
Content of B1 is: 
Content of B2 is: 00000000
Binary representation of 14 in 8 bit: 00001110
Content of B4 is: 0000000001010100

Content of B2 before set(): 00000000
Content of B2 after set(0): 00000001
Content of B2 after set(): 11111111
After resetting 2nd bit of B2: 11111101
After resetting every bit of B2: 00000000
Content of B3 before flip(): 00001110
Content of B3 after flip(0): 00001111
Content of B3 after flip():  11110000

Size of B1 is: 0
Size of B2 is: 8
Size of B3 is: 8
Size of B4 is: 16

B1 after increasing size to 4 bits: 0000
B1 after increasing size to 8 bits: 11110000
B1 after decreasing size to 1 bit:  0

B1 after push(1) operation:   10
B1 after push(0) operation : 010

B1 before pop operation: 010
B1 after pop operation:   10

Number of blocks in B4: 2

B1 is not empty
B2 is not empty
B3 is empty

Content of B4 is: 0000000001010100
Number of set bits in it are: 3

All bits in B2 are set
All bits in B2 are not set

Atleast one bit in B2 is set 
No bit in B2 is set 

None of the bits in B2 is set

Content of B1 is: 10
B1[1] is set

Операторы:
Некоторые из операторов, которые могут быть полезны для обработки битов:

  • operator [] : возвращает ссылку на n- й бит.
  • operator & = () : выполняет побитовое И с текущим объектом битового набора и объектом битового набора, переданным в аргументе. Например. B1.оператор & = (B2); побитовое И для B1 и B2, то есть B1 и B2 (B1 и B2 должны иметь одинаковое количество битов).
  • operator | = () : выполняет побитовое ИЛИ с текущим объектом битового набора и объектом битового набора, переданным в аргументе. Например. B1.оператор | = (B2); побитовое ИЛИ B1 и B2, т.е. B1 | B2 (B1 и B2 должны иметь одинаковое количество битов).
  • operator ^ = () : выполняет побитовое исключающее ИЛИ с текущим объектом битового набора и объектом битового набора, переданным в аргументе. Например. B1.оператор ^ = (B2); побитовое исключающее ИЛИ для B1 и B2, то есть B1 ^ B2 (B1 и B2 должны иметь одинаковое количество битов).
  • оператор - = () : он определяет разницу набора с текущим объектом битового набора и объектом битового набора, переданным в аргументе. Например. B1.оператор - = (B2); установить разность B1 и B2, т.е. B1 - B2 (B1 и B2 должны иметь одинаковое количество битов).
  • operator = () : присваивает текущему объекту битового набора объект, переданный в параметре.
  • operator == () : он проверяет, точно ли текущий объект битового набора передан как параметр.
  • operator! = () : он проверяет, не совпадает ли текущий объект битового набора с переданным в качестве параметра.
  • operator <() : возвращает истину, если текущий битовый набор лексикографически меньше, чем битовый объект, переданный как параметр, иначе он возвращает ложь.
  • operator> () : возвращает истину, если текущий битовый набор лексикографически больше, чем битовый объект, переданный как параметр, иначе он возвращает ложь.
  • operator <= () : возвращает истину, если текущий битовый набор лексикографически меньше или равен битовому объекту, переданному как параметр, иначе он возвращает ложь.
  • operator> = () : возвращает истину, если текущий битовый набор лексикографически больше или равен битовому объекту, переданному в качестве параметра, иначе он возвращает ложь.
  • оператор ~ () : он создает копию текущего битового набора со всеми его перевернутыми битами.
  • operator << () : создает копию текущего объекта битового набора, который сдвигается влево на n бит.
  • оператор >> () : он создает копию текущего объекта битового набора, который сдвигается вправо на n бит.
  • operator << = () : сдвигает текущий объект битового набора влево на n бит.
  • оператор >> = () : сдвигает текущий объект битового набора вправо на n бит.

Example 2:

#include <boost/dynamic_bitset.hpp>
#include <iostream>
using namespace std;
  
int main(int argc, char* argv[])
{
    int n_bits = 8;
  
    boost::dynamic_bitset<> B1(n_bits, 123);
    boost::dynamic_bitset<> B2(n_bits, 206);
    boost::dynamic_bitset<> temp(4, 3);
  
    cout << "Binary representation of 123: "
         << B1 << endl;
    cout << "Binary representation of 206: "
         << B2 << endl
         << endl;
  
    // Operator[] is used to access an individual index
    // It is a reference of the nth bit. It can be used for
    // assignment of a boolean value at nth bit
    cout << "4th bit of B1 consist: "
         << B1[3] << endl;
    B1[3] = 0;
    cout << "Assigning 0 to 4th bit of B1: "
         << B1 << endl
         << endl;
  
    // Operator= assigns on current bitset object
    cout << "temp before assignment: "
         << temp << endl;
  
    temp.operator=(B1);
    cout << "temp after assignment with B1: "
         << temp << endl
         << endl;
  
    // Operator&= performs bitwise-AND
    cout << "B1 consist of: "
         << B1 << endl;
    cout << "B2 consist of: "
         << B2 << endl;
  
    temp.operator=(B1);
    temp.operator&=(B2);
    cout << "B1 AND B2 is : & "
         << temp << endl
         << endl;
  
    // Operator|= performs bitwise-OR
    cout << "B1 consist of: "
         << B1 << endl;
    cout << "B2 consist of: "
         << B2 << endl;
  
    temp.operator=(B1);
    temp.operator|=(B2);
    cout << "B1 OR B2 is  : | "
         << temp << endl
         << endl;
  
    // Operator^= preforms bitwise-XOR
    cout << "B1 consist of: "
         << B1 << endl;
    cout << "B2 consist of: "
         << B2 << endl;
  
    temp.operator=(B1);
    temp.operator^=(B2);
    cout << "B1 XOR B2 is : ^ "
         << temp << endl
         << endl;
  
    // Operator-= performs set difference
    cout << "B1 consist of: "
         << B1 << endl;
    cout << "B2 consist of: "
         << B2 << endl;
  
    temp.operator=(B1);
    temp.operator-=(B2);
    cout << "Set differ is:   "
         << temp << endl
         << endl;
  
    // Operator== checks if bitset object is equal to
    // another one, bit length has to be same for true
    cout << "dynamic_bitset B1 and B2 are "
         << (operator==(B1, B2) ? "equal" : "not equal")
         << endl;
  
    boost::dynamic_bitset<> B3(2, 0), B4(3, 0);
    cout << "Content of B3: " << B3 << endl
         << "Content of B4: " << B4 << endl
         << "dynamic_bitset B3 and B4 are "
         << (operator==(B3, B4) ? "equal" : "not equal")
         << endl;
  
    B3.operator=(B4);
    cout << "dynamic_bitset B3 and B4 are: "
         << (operator==(B3, B4) ? "equal" : "not equal")
         << endl
         << endl;
  
    // Operator!= checks if bitset object is unequal
    cout << "dynamic_bitset B1 and B2 are ";
    cout << (operator!=(B1, B2) ? "not equal" : "equal")
         << endl
         << endl;
  
    // Operator< checks if first bitset object is
    // lexicographically less than second one
    cout << "B1 consist of: " << B1 << endl;
    cout << "B2 consist of: " << B2 << endl;
  
    if (operator<(B1, B2))
        cout << "B1 is lexicographically less than B2";
    else
        cout << "B2 is lexicographically greater than B2";
    cout &
C++