Поделиться через


Класс bitset

Описывает тип объекта, который хранит последовательность, состоящую из фиксированного числа битов, предоставляющих компактный способ хранения флагов для набора элементов или условий. Класс bitset поддерживает операции с объектами набора типов, которые содержат коллекцию битов и предоставляют постоянный доступ к каждому биту.

Синтаксис

template <size_t N>
class bitset

Параметры

N
Указывает количество битов в bitset объекте с целым числом ненулевого типа size_t , которое должно быть известно во время компиляции.

Замечания

В отличие от аналогичного vector<bool> класса, bitset класс не имеет итераторов и не является контейнером стандартной библиотеки C++. Он также отличается от vector<bool> определенного размера, фиксированного во время компиляции в соответствии с размером, указанным параметром N шаблона при bitset<N> объявлении.

Бит задан, если его значение равно 1, и сброшен, если его значение равно 0. Перевернуть или инвертировать бит — значит изменить его значение с 1 на 0 или с 0 на 1. N Биты в индексируются bitset целыми значениями от 0 до N 1, где 0 индексирует первую битовую позицию и N - 1 окончательное битовое положение.

Участники

Конструкторы

Имя Описание
bitset Создает объект класса bitset<N> и инициализирует биты с нулевым значением до определенного указанного значения или до значений, полученных из символов в строке.

Определения типов

Имя Описание
element_type Тип, который служит синонимом типа данных bool и может использоваться для ссылки на биты элементов в bitset.

Функции

Имя Описание
all Проверяет все биты в этом bitset параметре, чтобы определить, задано ли оно.true
any Функция-член проверяет, равен ли какой-либо бит в последовательности 1.
count Эта функция-член возвращает количество бит, заданных в последовательности бит.
flip Инвертирует все биты в bitset или инвертирует один бит в указанной позиции.
none Проверяет, присвоено ли хотя бы одному биту в объекте bitset значение 1.
reset Сбрасывает все биты в bitset в значение 0 или сбрасывает бит в указанной позиции в 0.
set Присваивает всем битам в bitset значение 1 или присваивает биту в указанной позиции значение 1.
size Возвращает количество бит в объекте bitset.
test Проверяет, присвоено ли биту в указанной позиции в bitset значение 1.
to_string Преобразует объект bitset в строковое представление.
to_ullong Возвращает сумму значений бит в bitset как unsigned long long.
to_ulong Преобразует объект bitset в unsigned long, чтобы получить последовательность его битов, если используется для инициализации bitset.

Классы

Имя Описание
reference Прокси-класс, который предоставляет ссылки на биты в объекте bitset, используемые для доступа к отдельным битам и их обработки в качестве вспомогательного класса для operator[] класса bitset.

Операторы

Имя Описание
operator!= Проверяет целевой объект bitset на неравенство относительно указанного объекта bitset.
operator&= Выполняет побитовое сочетание битовых наборов с побитовой операцией "и" (&).
operator<< Сдвигает биты в bitset влево на указанное число позиций и возвращает результат в новом объекте bitset.
operator<<= Сдвигает биты в bitset влево на указанное число позиций и возвращает результат в целевом объекте bitset.
operator== Проверяет целевой объект bitset на равенство относительно указанного объекта bitset.
operator>> Сдвигает биты в bitset вправо на указанное число позиций и возвращает результат в новом объекте bitset.
operator>>= Сдвигает биты в bitset вправо на указанное число позиций и возвращает результат в целевом объекте bitset.
operator[] Возвращает ссылку на бит в указанной позиции в bitset, если bitset может быть изменен; в противном случае возвращается значение бита в этой позиции.
оператор^= Выполняет побитовое сочетание битовых наборов с побитовой операцией xor (^).
operator|= Выполняет побитовое сочетание битовых наборов с побитовой операцией "или" (|).
operator~ Инвертирует все биты в целевом объекте bitset и возвращает результат.

Структуры

Имя Описание
hash

all

Проверяет все биты в этом битовом наборе, чтобы определить, задано ли значение true.

bool all() const;

Возвращаемое значение

Возвращает значение true , если все биты этого набора имеют значение true. Возвращает значение false , если один или несколько битов имеют значение false.

any

Проверяет, равен ли какой-либо бит в последовательности 1.

bool any() const;

Возвращаемое значение

true Значение 1, если бит в этом bitset параметре задано значение 1; false если все биты равны 0.

Пример

// bitset_any.cpp
// compile with: /EHsc
#include <bitset>
#include <iostream>

int main( )
{
   using namespace std;

   bitset<5> b1 ( 6 );
   bool b, rb;

   cout << "The original bitset b1( 6 ) is: ( "<< b1 << " )"
        << endl;

   b = b1.any ( );

   if ( b )
      cout << "At least one of the bits in bitset is set to 1."
           << endl;
   else
      cout << "None of the bits in bitset are set to 1."
           << endl;

   bitset<5> rb1;
   rb1 = b1.reset ( );

   cout << "The reset bitset is: ( "<< b1 << " )"
        << endl;

   rb = rb1.any ( );

   if ( rb )
      cout << "At least one of the bits in the reset bitset "
           << "are set to 1." << endl;
   else
      cout << "None of the bits in bitset b1 are set to 1."
           << endl;
}
The original bitset b1( 6 ) is: ( 00110 )
At least one of the bits in bitset is set to 1.
The reset bitset is: ( 00000 )
None of the bits in bitset b1 are set to 1.

bitset

Создает объект класса bitset<N> и инициализирует биты с нулевым значением, с определенным указанным значением или со значениями, полученными из символов в строке.

1) constexpr bitset();
2) bitset(unsigned long val);
3) constexpr bitset(unsigned long long val);
4) template <class CharType, class Traits, class Allocator>
    explicit bitset(
        const basic_string<CharType, Traits, Allocator>& str,
        typename basic_string<CharType, Traits, Allocator>::size_type pos = 0);
    
5) template <class CharType, class Traits, class Allocator>
    explicit bitset(
        const basic_string<CharType, Traits, Allocator>& str,
        typename basic_string<CharType, Traits, Allocator>::size_type pos,
        typename basic_string<CharType, Traits, Allocator>::size_type count,
        CharType Zero = CharType ('0'),
        CharType One = CharType ('1'));
    
6) template<class CharType>
    explicit bitset(
        const CharType* str,
        typename basic_string<CharType>::size_type
        n = basic_string<CharType>::npos,
        CharType zero = CharType('0'),
        CharType one = CharType('1'));

Параметры

val
Целое число без знака, базовое представление которого используется для инициализации битов в создаваемом bitset .

str
Строка нулей и тех, которые используются для инициализации битовых значений bitset .

pos
Позиция символа в строке, подсчет от левого к правому краю и начиная с нуля, используемая для инициализации первого бита в строке bitset.

count
Число символов в строке, используемой для предоставления начальных значений битов в строке bitset.

Zero
Символ, который используется для представления нуля. Значение по умолчанию — 0.

One
Символ, который используется для представления единицы. Значение по умолчанию — 1.

Замечания

1) Создает объект класса bitset<N> и инициализирует все N-биты до значения по умолчанию нуля.

2-3) Создает объект класса bitset<N> и инициализирует биты из val параметра.

4) Создает объект класса bitset<N> и инициализирует биты из символов, предоставленных в строке нулей и тех. Если какие-либо символы строки отличаются от 0 или 1, конструктор создает объект класса invalid argument. Если указанная позиция (pos) превышает длину строки, конструктор создает объект класса out_of_range. Конструктор задает только те биты в позиции j , bitset для которой символ строки в позиции pos + j равен 1. По умолчанию pos — 0.

5)4) Аналогично другому параметру, countкоторый указывает количество битов для инициализации. Он имеет два необязательных параметра, _Zero а _Oneтакже указывает, какой символ str должен интерпретироваться, чтобы означать 0 бит и 1 бит соответственно.

6) Создает объект класса bitset<N>, инициализируя N-биты значениям, которые соответствуют символам, предоставленным в строке символов в стиле C, равных нулям и тем. Например, конструктор вызывается без приведения строки в тип строки: bitset<5> b5("01011");

Пример

// bitset_bitset.cpp
// compile with: /EHsc
#include <bitset>
#include <iostream>

int main( )
{
   // Using the default constructor
   using namespace std;
   bitset<2> b0;
   cout << "The set of bits in bitset<2> b0 is: ( "
        << b0 << " )." << endl;

   // Using the second member function
   bitset<5> b1 ( 6 );
   cout << "The set of bits in bitset<5> b1( 6 ) is: ( "
        << b1 << " )." << endl;

   // The template parameter N can be an expression
   bitset< 2 * sizeof ( int ) > b2;
   cout << "The set of bits in bitset< 2 * sizeof ( int ) > b2 is: ( "
        << b2 << " )." << endl;

   // The base two representation will be truncated
   // if its length exceeds the size of the bitset
   bitset<3> b3 ( 6 );
   cout << "The set of bits in bitset<3> b3( 6 ) is ( "
        << b3 << " )." << endl;

   // Using a c-style string to initialize the bitset
    bitset<7> b3andahalf ( "1001001" );
    cout << "The set of bits in bitset<7> b3andahalf ( \"1001001\" )"
         << " is ( " << b3andahalf << " )." << endl;

   // Using the fifth member function with the first parameter
   string bitval4 ( "10011" );
   bitset<5> b4 ( bitval4 );
   cout << "The set of bits in bitset<5> b4( bitval4 ) is ( "
        << b4 << " )." << endl;

   // Only part of the string may be used for initialization

   // Starting at position 3 for a length of 6 (100110)
   string bitval5 ("11110011011");
   bitset<6> b5 ( bitval5, 3, 6 );
   cout << "The set of bits in bitset<11> b5( bitval, 3, 6 ) is ( "
        << b5 << " )." << endl;

   // The bits not initialized with part of the string
   // will default to zero
   bitset<11> b6 ( bitval5, 3, 5 );
   cout << "The set of bits in bitset<11> b6( bitval5, 3, 5 ) is ( "
        << b6 << " )." << endl;

   // Starting at position 2 and continue to the end of the string
   bitset<9> b7 ( bitval5, 2 );
   cout << "The set of bits in bitset<9> b7( bitval, 2 ) is ( "
        << b7 << " )." << endl;
}
The set of bits in bitset<2> b0 is: ( 00 ).
The set of bits in bitset<5> b1( 6 ) is: ( 00110 ).
The set of bits in bitset<2 * sizeof ( int ) > b2 is: ( 00000000 ).
The set of bits in bitset<3> b3( 6 ) is ( 110 ).
The set of bits in bitset<5> b4( bitval4 ) is ( 10011 ).
The set of bits in bitset<11> b5( bitval, 3, 6 ) is ( 100110 ).
The set of bits in bitset<11> b6( bitval5, 3, 5 ) is ( 00000010011 ).
The set of bits in bitset<9> b7( bitval, 2 ) is ( 110011011 ).

count

Возвращает количество бит, заданных в последовательности бит.

size_t count() const;

Возвращаемое значение

Количество бит, заданных в последовательности бит.

Пример

// bitset_count.cpp
// compile with: /EHsc
#include <bitset>
#include <iostream>

int main( )
{
    using namespace std;

    bitset<5> b1(4);

    cout << "The collection of bits in the original bitset is: ( "
         << b1 << " )" << endl;

    size_t i;
    i = b1.count();
    cout << "The number of bits in the bitset set to 1 is: "
         << i << "." << endl;

    bitset<5> fb1;
    fb1 = b1.flip();

    cout << "The collection of flipped bits in the modified bitset "
         << "is: ( " << b1 << " )" << endl;

    size_t ii;
    ii = fb1.count();
    cout << "The number of bits in the bitset set to 1 is: "
         << ii << "." << endl;
}
The collection of bits in the original bitset is: ( 00100 )
The number of bits in the bitset set to 1 is: 1.
The collection of flipped bits in the modified bitset is: ( 11011 )
The number of bits in the bitset set to 1 is: 4.

element_type

Тип, который служит синонимом типа данных bool и может использоваться для ссылки на биты элементов в bitset.

typedef bool element_type;

Пример

// bitset_elem_type.cpp
// compile with: /EHsc
#include <bitset>
#include <iostream>

int main( )
{
   using namespace std;

   bitset<3> b1 ( 2 );
   cout << "Original bitset b1(6) is: ( "<< b1 << " )"
        << endl;

   //Compare two ways to reference bits in a bitset
   bool b;
   bitset<5>::element_type e;

   b = b1.test ( 2 );
   if ( b )
      cout << "The bit at position 2 of bitset b1"
           << "has a value of 1." << endl;
   else
      cout << "The bit at position 2 of bitset b1"
           << "has a value of 0." << endl;
   b1[2] = 1;
   cout << "Bitset b1 modified by b1[2] = 1 is: ( "<< b1 << " )"
        << endl;

   e = b1.test ( 2 );
   if ( e )
      cout << "The bit at position 2 of bitset b1"
           << "has a value of 1." << endl;
   else
      cout << "The bit at position 2 of bitset b1"
           << "has a value of 0." << endl;
}
Original bitset b1(6) is: ( 010 )
The bit at position 2 of bitset b1has a value of 0.
Bitset b1 modified by b1[2] = 1 is: ( 110 )
The bit at position 2 of bitset b1has a value of 1.

flip

Инвертирует все биты в bitset или инвертирует один бит в указанной позиции.

bitset<N>& flip();
bitset<N>& flip(size_t pos);

Параметры

pos
Позиция бита, значение которого следует инвертировать.

Возвращаемое значение

Копия измененного bitset объекта, для которого была вызвана функция-член.

Замечания

Вторая функция-член создает out_of_range исключение, если позиция, указанная в качестве параметра, больше размера N бита bitset<N> которого была инвертирована.

Пример

// bitset_flip.cpp
// compile with: /EHsc
#include <bitset>
#include <iostream>

int main( )
{
   using namespace std;
   bitset<5> b1 ( 6 );

   cout << "The collection of bits in the original bitset is: ( "
        << b1 << " )" << endl;

   bitset<5> fb1;
   fb1 = b1.flip ( );

   cout << "After flipping all the bits, the bitset becomes: ( "
        << fb1 << " )" << endl;

   bitset<5> f3b1;
   f3b1 = b1.flip ( 3 );

   cout << "After flipping the fourth bit, the bitset becomes: ( "
        << f3b1 << " )" << endl << endl;

   bitset<5> b2;
   int i;
   for ( i = 0 ; i <= 4 ; i++ )
   {
      b2.flip(i);
      cout << b2 << "  The bit flipped is in position "
           << i << ".\n";
   }
}
The collection of bits in the original bitset is: ( 00110 )
After flipping all the bits, the bitset becomes: ( 11001 )
After flipping the fourth bit, the bitset becomes: ( 10001 )

00001  The bit flipped is in position 0.
00011  The bit flipped is in position 1.
00111  The bit flipped is in position 2.
01111  The bit flipped is in position 3.
11111  The bit flipped is in position 4.

hash

template <class T> struct hash;
template <size_t N> struct hash<bitset<N>>;

нет

Проверяет, присвоено ли хотя бы одному биту в объекте bitset значение 1.

bool none() const;

Возвращаемое значение

true Значение 1, если бит в ней bitset не задан; false если по крайней мере один бит был установлен на 1.

Пример

// bitset_none.cpp
// compile with: /EHsc
#include <bitset>
#include <iostream>

int main( )
{
   using namespace std;

   bitset<5> b1 ( 6 );
   bool b, rb;

   cout << "Original bitset b1(6) is: ( " << b1 << " )"
        << endl;

   b = b1.none ( );

   if ( b )
      cout << "None of the bits in bitset b1 are set to 1."
           << endl;
   else
      cout << "At least one of the bits in bitset b1 is set to 1."
           << endl;

   bitset<5> rb1;
   rb1 = b1.reset ( );
   rb = rb1.none ( );
   if ( rb )
      cout << "None of the bits in bitset b1 are set to 1."
           << endl;
   else
      cout << "At least one of the bits in bitset b1 is set to 1."
           << endl;
}
Original bitset b1(6) is: ( 00110 )
At least one of the bits in bitset b1 is set to 1.
None of the bits in bitset b1 are set to 1.

operator!=

Проверяет целевой битовый массив на неравенство относительно указанного битового массива.

bool operator!=(const bitset<N>& right) const;

Параметры

right
Значение bitset , которое необходимо сравнить с целевым набором битов для неравенства.

Возвращаемое значение

true Значение , если битовые наборы отличаются; false Если они одинаковы.

Замечания

Битовые наборы должны иметь одинаковый размер.

Пример

// bitset_op_NE.cpp
// compile with: /EHsc
#include <bitset>
#include <iostream>

int main( )
{
   using namespace std;

   bitset<5> b1 ( 7 );
   bitset<5> b2 ( 7 );
   bitset<5> b3 ( 2 );
   bitset<4> b4 ( 7 );

   if ( b1 != b2 )
      cout << "Bitset b1 is different from bitset b2." << endl;
   else
      cout << "Bitset b1 is the same as bitset b2." << endl;

   if ( b1 != b3 )
      cout << "Bitset b1 is different from bitset b3." << endl;
   else
      cout << "Bitset b1 is the same as bitset b3." << endl;

   // This would cause an error because bitsets must have the
   // same size to be tested
   // if ( b1 != b4 )
   //   cout << "Bitset b1 is different from bitset b4." << endl;
   // else
   //   cout << "Bitset b1 is the same as bitset b4." << endl;
}
Bitset b1 is the same as bitset b2.
Bitset b1 is different from bitset b3.

operator&=

Выполняет побитовое сочетание битовых наборов с побитовой операцией "и" (&).

bitset<N>& operator&=(const bitset<N>& right);

Параметры

right
То bitset , что должно быть объединено побитово с целевым набором битов.

Возвращаемое значение

Измененный целевой битовый набор, который приводит к побитовой операции "and" (&) с bitset указанным в качестве параметра.

Замечания

Два бита, объединенные оператором AND , возвращаются true , если каждый бит имеет значение true; в противном случае их комбинация возвращается false.

Два битовых набора должны иметь одинаковый размер.

Пример

// bitset_op_bitwise.cpp
// compile with: /EHsc
#include <bitset>
#include <iostream>

int main( )
{
   using namespace std;

   bitset<5> b1 ( 7 );
   bitset<5> b2 ( 11 );
   bitset<4> b3 ( 7 );

   cout << "The target bitset b1 is:    ( "<< b1 << " )." << endl;
   cout << "The parameter bitset b2 is: ( "<< b2 << " )." << endl;
   cout << endl;

   b1 &= b2;
   cout << "After bitwise AND combination,\n"
        << "the target bitset b1 becomes:   ( "<< b1 << " )."
        << endl;

   // Note that the parameter-specified bitset is unchanged
   cout << "The parameter bitset b2 remains: ( "<< b2 << " )."
        << endl;

   // The following would cause an error because the bisets
   // must be of the same size to be combined
   // b1 &= b3;
}
The target bitset b1 is:    ( 00111 ).
The parameter bitset b2 is: ( 01011 ).

After bitwise AND combination,
the target bitset b1 becomes:   ( 00011 ).
The parameter bitset b2 remains: ( 01011 ).

operator<<

Сдвигает биты в bitset влево на указанное число позиций и возвращает результат в новом объекте bitset.

bitset<N> operator<<(size_t pos) const;

Параметры

pos
Количество позиций влево, которое должны быть смещены биты в нем bitset .

Возвращаемое значение

Измененный битовый массив с битами, сдвинутыми влево на требуемое количество позиций.

Замечания

Функция оператора-члена возвращает bitset(*this) <<= pos , где <<= сдвигает биты влево bitset на указанное количество позиций и возвращает результат целевому bitsetобъекту.

Пример

// bitset_op_LS.cpp
// compile with: /EHsc
#include <bitset>
#include <iostream>

int main( )
{
   using namespace std;

   bitset<5> b1 ( 7 );

   cout << "The bitset b1 is: ( "<< b1 << " )." << endl;

   bitset<5> b2;
   b2 = b1 << 2;

   cout << "After shifting the bits 2 positions to the left,\n"
        << " the bitset b2 is: ( "<< b2 << " )."
        << endl;

   bitset<5> b3 = b2 >> 1;

   cout << "After shifting the bits 1 position to the right,\n"
        << " the bitset b3 is: ( " << b3 << " )."
        << endl;
}

operator<<=

Сдвигает биты в bitset влево на указанное число позиций и возвращает результат в целевом объекте bitset.

bitset<N>& operator<<=(size_t pos);

Параметры

pos
Количество позиций слева от битов в нем bitset должно быть смещено.

Возвращаемое значение

Целевое bitset изменение, чтобы биты были перемещены влево, чтобы требуемое количество позиций.

Замечания

Если отсутствуют элементы для сдвига в эту позицию, функция сбрасывает бит в значение 0.

Пример

// bitset_op_LSE.cpp
// compile with: /EHsc
#include <bitset>
#include <iostream>

int main( )
{
   using namespace std;
   bitset<5> b1 ( 7 );
   cout << "The target bitset b1 is: ( "<< b1 << " )." << endl;
   b1 <<= 2;
   cout << "After shifting the bits 2 positions to the left,\n"
        << "the target bitset b1 becomes: ( "<< b1 << " )."
        << endl;
}
The target bitset b1 is: ( 00111 ).
After shifting the bits 2 positions to the left,
the target bitset b1 becomes: ( 11100 ).

operator==

Проверяет целевой битовый массив на равенство относительно указанного битового массива.

bool operator==(const bitset<N>& right) const;

Параметры

right
Значение bitset , которое необходимо сравнить с целевым набором битов для равенства.

Возвращаемое значение

true Значение , если наборы одинаковы; false Если они отличаются.

Замечания

Битовые наборы должны иметь одинаковый размер.

Пример

// bitset_op_EQ.cpp
// compile with: /EHsc
#include <bitset>
#include <iostream>

int main( )
{
   using namespace std;
   bitset<5> b1 ( 7 );
   bitset<5> b2 ( 7 );
   bitset<5> b3 ( 2 );
   bitset<4> b4 ( 7 );

   if ( b1 == b2 )
      cout << "Bitset b1 is the same as bitset b2." << endl;
   else
      cout << "Bitset b1 is different from bitset b2." << endl;

   if ( b1 == b3 )
      cout << "Bitset b1 is the same as bitset b3." << endl;
   else
      cout << "Bitset b1 is different from bitset b3." << endl;

   // This would cause an error because bitsets must have the
   // same size to be tested
   // if ( b1 == b4 )
   //   cout << "Bitset b1 is the same as bitset b4." << endl;
   // else
   //   cout << "Bitset b1 is different from bitset b4." << endl;
}
Bitset b1 is the same as bitset b2.
Bitset b1 is different from bitset b3.

operator>>

Сдвигает биты вправо bitset на указанное количество позиций и возвращает результат в новый битовый набор.

bitset<N> operator>>(size_t pos) const;

Параметры

pos
Количество позиций справа от битов в нем bitset должно быть смещено.

Возвращаемое значение

Новый набор битов, где биты были перемещены вправо, требуемое количество позиций относительно целевого bitset.

Пример

// bitset_op_RS.cpp
// compile with: /EHsc
#include <bitset>
#include <iostream>

int main( )
{
   using namespace std;
   bitset<5> b1 ( 7 );
   cout << "The bitset b1 is: ( "<< b1 << " )." << endl;

   bitset<5> b2;
   b2 = b1 << 2;

   cout << "After shifting the bits 2 positions to the left,\n"
        << "the bitset b2 is: ( "<< b2 << " )."
        << endl;
   bitset<5> b3 = b2 >> 1;

   cout << "After shifting the bits 1 position to the right,\n"
        << "the bitset b3 is: ( " << b3 << " )."
        << endl;
}
The bitset b1 is: ( 00111 ).
After shifting the bits 2 positions to the left,
the bitset b2 is: ( 11100 ).
After shifting the bits 1 position to the right,
the bitset b3 is: ( 01110 ).

operator>>=

Сдвигает биты в bitset вправо на указанное число позиций и возвращает результат в целевом объекте bitset.

bitset<N>& operator>>=(size_t pos);

Параметры

pos
Количество позиций справа от битов в нем bitset должно быть смещено.

Возвращаемое значение

Целевое bitset изменение, чтобы биты были смещены вправо на требуемое количество позиций.

Замечания

Если отсутствуют элементы для сдвига в эту позицию, функция сбрасывает бит в значение 0.

Пример

// bitset_op_RSE.cpp
// compile with: /EHsc
#include <bitset>
#include <iostream>

int main( )
{
   using namespace std;
   bitset<5> b1 ( 28 );
   cout << "The target bitset b1 is: ( "<< b1 << " )." << endl;

   b1 >>= 2;
   cout << "After shifting the bits 2 positions to the right,\n"
        << "the target bitset b1 becomes: ( "<< b1 << " )."
        << endl;
}
The target bitset b1 is: ( 11100 ).
After shifting the bits 2 positions to the right,
the target bitset b1 becomes: ( 00111 ).

operator[]

Возвращает ссылку на бит в указанной позиции в bitset, если bitset может быть изменен; в противном случае возвращается значение бита в этой позиции.

bool operator[](size_t pos) const;
reference operator[](size_t pos);

Параметры

pos
Позиция, расположенная внутри бита bitset.

Замечания

При определении _ITERATOR_DEBUG_LEVEL как 1 или 2 в сборке в исполняемом файле возникнет ошибка среды выполнения, если вы пытаетесь получить доступ к элементу за пределами границ.bitset Дополнительные сведения см. в разделе Проверяемые итераторы.

Пример

// bitset_op_REF.cpp
// compile with: /EHsc
#include <bitset>
#include <iostream>

int main( )
{
   using namespace std;
   bool b;
   bitset<5> b1 ( 6 );
   cout << "The initialized bitset<5> b1( 2 ) is: ( "<< b1 << " )."
        << endl;

   int i;
   for ( i = 0 ; i <= 4 ; i++ )
   {
      b = b1[ i ];
      cout << "  The bit in position "
           << i << " is " << b << ".\n";
   }
}

operator^=

Выполняет побитовое сочетание битовых наборов с побитовой операцией xor (^).

bitset<N>& operator^=(const bitset<N>& right);

Параметры

right
То bitset , что должно быть объединено побитово с целевым набором битов.

Возвращаемое значение

Измененный целевой набор, который приводит к побитовой операции xor (^) с bitset указанным в качестве параметра.

Замечания

Два бита в сочетании с побитовой оператором xor (^) возвращаются true , если по крайней мере один, но не оба бита true; в противном случае их комбинация возвращается false.

Битовые наборы должны иметь одинаковый размер.

Пример

// bitset_op_bitwiseOR.cpp
// compile with: /EHsc
#include <bitset>
#include <iostream>

int main( )
{
   using namespace std;
   bitset<5> b1 ( 7 );
   bitset<5> b2 ( 11 );
   bitset<4> b3 ( 7 );

   cout << "The target bitset b1 is:    ( "<< b1 << " )." << endl;
   cout << "The parameter bitset b2 is: ( "<< b2 << " )." << endl;
   cout << endl;

   b1 ^= b2;
   cout << "After bitwise exclusive OR combination,\n"
        << "the target bitset b1 becomes:   ( "<< b1 << " )."
        << endl;

   // Note that the parameter-specified bitset in unchanged
   cout << "The parameter bitset b2 remains: ( "<< b2 << " )."
        << endl;

   // The following would cause an error because the bitsets
   // must be of the same size to be combined
   // b1 |= b3;
}
The target bitset b1 is:    ( 00111 ).
The parameter bitset b2 is: ( 01011 ).

After bitwise exclusive OR combination,
the target bitset b1 becomes:   ( 01100 ).
The parameter bitset b2 remains: ( 01011 ).

operator|=

Объединяет два битовых набора с помощью побитовой операции "или" (|).

bitset<N>& operator|=(const bitset<N>& right);

Параметры

right
То bitset , что должно быть объединено побитово с целевым bitsetобъектом.

Возвращаемое значение

Измененный целевой набор битов, который приводит к побитовой операции "or" (|) с bitset указанным в качестве параметра.

Замечания

Два бита, объединенные оператором инклюзивного, возвращаютсяtrue, если по крайней мере один из битов true; если оба бита являютсяfalse, их комбинация возвращаетсяfalse.OR

Битовые наборы должны иметь одинаковый размер.

Пример

// bitset_op_BIO.cpp
// compile with: /EHsc
#include <bitset>
#include <iostream>

int main( )
{
   using namespace std;

   bitset<5> b1 ( 7 );
   bitset<5> b2 ( 11 );
   bitset<4> b3 ( 7 );

   cout << "The target bitset b1 is:    ( "<< b1 << " )." << endl;
   cout << "The parameter bitset b2 is: ( "<< b2 << " )." << endl;
   cout << endl;

   b1 |= b2;
   cout << "After bitwise inclusive OR combination,\n"
        << "the target bitset b1 becomes:   ( "<< b1 << " )."
        << endl;

   // Note that the parameter-specified bitset in unchanged
   cout << "The parameter bitset b2 remains: ( "<< b2 << " )."
        << endl;

   // The following would cause an error because the bisets
   // must be of the same size to be combined
   // b1 |= b3;
}
The target bitset b1 is:    ( 00111 ).
The parameter bitset b2 is: ( 01011 ).

After bitwise inclusive OR combination,
the target bitset b1 becomes:   ( 01111 ).
The parameter bitset b2 remains: ( 01011 ).

operator~

Инвертирует все биты в целевом битовом массиве и возвращает результат.

bitset<N> operator~() const;

Возвращаемое значение

Все bitset его биты вращились относительно целевого bitsetобъекта.

Пример

// bitset_op_invert.cpp
// compile with: /EHsc
#include <iostream>
#include <string>
#include <bitset>

int main( )
{
   using namespace std;

   bitset<5> b1 ( 7 );
   bitset<5> b2;
   b2 = ~b1;

   cout << "Bitset b1 is: ( "<< b1 << " )." << endl;
   cout << "Bitset b2 = ~b1 is: ( "<< b2 << " )." << endl;

   // These bits could also be flipped using the flip member function
   bitset<5> b3;
   b3 = b1.flip( );
   cout << "Bitset b3 = b1.flip( ) is: ( "<< b2 << " )." << endl;
}
Bitset b1 is: ( 00111 ).
Bitset b2 = ~b1 is: ( 11000 ).
Bitset b3 = b1.flip( ) is: ( 11000 ).

reference

Прокси-класс, который предоставляет ссылки на биты в объекте bitset, используемые для доступа к отдельным битам и их обработки в качестве вспомогательного класса для operator[] класса bitset.

class reference {
   friend class bitset<N>;
public:
   reference& operator=(bool val);
   reference& operator=(const reference& bitref);
   bool operator~() const;
   operator bool() const;
   reference& flip();
};

Параметры

val
Значение объекта типа bool , назначаемого биту в бите bitset.

bitref
Ссылка на форму x [ i ] на бит в позицииbitsetix.

Возвращаемое значение

Ссылка на бит в bitset указанной позицией аргумента для первой, второй и пятой функций-членов ссылок на класс и true или false, чтобы отразить значение измененного бита в bitset третий и четвертый член ссылок на класс.

Замечания

Класс reference существует только как вспомогательный класс для bitsetoperator[]. Класс-член описывает объект, который может получить доступ к отдельному биту в пределах bitsetобъекта. Позвольте b быть объектом типа и xy объектами типаboolbitset<N>, а также ij допустимыми позициями в таком объекте. Нотация x [i] ссылается на бит в позиции i в битовом наборе x. Функции — члены класса reference предоставляют по порядку следующие операции.

Операция Определение
x[i] = b Сохраняет bool значение b в битовом расположении i в битовом наборе x.
x[i] = y[j] Сохраняет значение бита y[ j] в битовом расположении i в битовом наборе x.
b = ~ x[i] Сохраняет перевернутое значение бита x[ i] в boolb.
b = x[i] Сохраняет значение бита x[ i] в boolb.
x[i]. flip( ) Сохраняет перевернутое значение бита x[ i] обратно в xбитовом положенииi.

Пример

// bitset_reference.cpp
// compile with: /EHsc
#include <bitset>
#include <iostream>

int main( )
{
   using namespace std;

   bitset<5> b1 ( 2 );
   bitset<5> b2 ( 6 );
   cout << "The initialized bitset<5> b1( 2 ) is: ( "<< b1 << " )."
        << endl;
   cout << "The initialized bitset<5> b2( 6 ) is: ( "<< b2 << " )."
        << endl;

   // Example of x [i] = b storing bool b at bit position i
   // in bitset x
   b1[ 0 ] = true;
   cout << "The bitset<5> b1 with the bit at position 0 set to 1"
        << "is: ( "<< b1 << " )" << endl;

   // Example of x [i] = y [j] storing the bool value of the
   // bit at position j in bitset y at bit position i in bitset x
   b2 [4] = b1 [0];      // b1 [0] = true
   cout << "The bitset<5> b2 with the bit at position 4 set to the "
        << "value\nof the bit at position 0 of the bit in "
        << "bitset<5> b1 is: ( "<<  b2  << " )" << endl;

   // Example of b = ~x [i] flipping the value of the bit at
   // position i of bitset x and storing the value in an
   // object b of type bool
   bool b = ~b2 [4];      // b2 [4] = false
   if ( b )
      cout << "The value of the object b = ~b2 [4] "
           << "of type bool is true." << endl;
   else
      cout << "The value of the object b = ~b2 [4] "
           << "of type bool is false." << endl;

   // Example of b = x [i] storing the value of the bit at
   // position i of bitset x in the object b of type bool
   b = b2 [4];
   if ( b )
      cout << "The value of the object b = b2 [4] "
           << "of type bool is true." << endl;
   else
      cout << "The value of the object b = b2 [4] "
           << "of type bool is false." << endl;

   // Example of x [i] . flip ( ) toggling the value of the bit at
   // position i of bitset x
   cout << "Before flipping the value of the bit at position 4 in "
        << "bitset b2,\nit is ( "<<  b2  << " )." << endl;
   b2 [4].flip( );
   cout << "After flipping the value of the bit at position 4 in "
        << "bitset b2,\nit becomes ( "<<  b2  << " )." << endl;
   bool c;
   c = b2 [4].flip( );
   cout << "After a second flip, the value of the position 4 "
        << "bit in b2 is now: " << c << ".";
}
The initialized bitset<5> b1( 2 ) is: ( 00010 ).
The initialized bitset<5> b2( 6 ) is: ( 00110 ).
The bitset<5> b1 with the bit at position 0 set to 1 is: ( 00011 )
The bitset<5> b2 with the bit at position 4 set to the value
of the bit at position 0 of the bit in bitset<5> b1 is: ( 10110 )
The value of the object b = ~b2 [4] of type bool is false.
The value of the object b = b2 [4] of type bool is true.
Before flipping the value of the bit at position 4 in bitset b2,
it is ( 10110 ).
After flipping the value of the bit at position 4 in bitset b2,
it becomes ( 00110 ).
After a second flip, the value of the position 4 bit in b2 is now: 1.

reset

Сбрасывает все биты в bitset в значение 0 или сбрасывает бит в указанной позиции в 0.

bitset<N>& reset();
bitset<N>& reset(size_t pos);

Параметры

pos
Положение бита в бите bitset для сброса до 0.

Возвращаемое значение

Копия bitset , для которой была вызвана функция-член.

Замечания

Вторая функция-член создает out_of_range исключение, если указанное положение больше размера bitset.

Пример

// bitset_reset.cpp
// compile with: /EHsc
#include <bitset>
#include <iostream>

int main( )
{
   using namespace std;

   bitset<5> b1 ( 13 );
   cout << "The set of bits in bitset<5> b1(13) is: ( "<< b1 << " )"
        << endl;

   bitset<5> b1r3;
   b1r3 = b1.reset( 2 );
   cout << "The collection of bits obtained from resetting the\n"
        << "third bit of bitset b1 is: ( "<< b1r3 << " )"
        << endl;

   bitset<5> b1r;
   b1r = b1.reset( );
   cout << "The collecion of bits obtained from resetting all\n"
        << "the elements of the bitset b1 is: ( "<< b1r << " )"
        << endl;
}
The set of bits in bitset<5> b1(13) is: ( 01101 )
The collecion of bits obtained from resetting the
third bit of bitset b1 is: ( 01001 )
The collecion of bits obtained from resetting all
the elements of the bitset b1 is: ( 00000 )

set

Присваивает всем битам в bitset значение 1 или присваивает биту в указанной позиции значение 1.

bitset<N>& set();

bitset<N>& set(
    size_t pos,
    bool val = true);

Параметры

pos
Положение бита в bitset заданном значении.

val
Значение, назначенное биту в указанной позиции.

Возвращаемое значение

Копия bitset , для которой была вызвана функция-член.

Замечания

Вторая функция-член создает out_of_range исключение, если указанное положение больше размера bitset.

Пример

// bitset_set.cpp
// compile with: /EHsc
#include <bitset>
#include <iostream>

int main( )
{
   using namespace std;

   bitset<5> b1 ( 6 );
   cout << "The set of bits in bitset<5> b1(6) is: ( "<< b1 << " )"
        << endl;

   bitset<5> b1s0;
   b1s0 = b1.set( 0 );
   cout << "The collecion of bits obtained from setting the\n"
        << "zeroth bit of bitset b1 is: ( "<< b1s0 << " )"
        << endl;

   bitset<5> bs1;
   bs1 = b1.set( );
   cout << "The collecion of bits obtained from setting all the\n"
        << "elements of the bitset b1 is: ( "<< bs1 << " )"
        << endl;
}
The set of bits in bitset<5> b1(6) is: ( 00110 )
The collecion of bits obtained from setting the
zeroth bit of bitset b1 is: ( 00111 )
The collecion of bits obtained from setting all the
elements of the bitset b1 is: ( 11111 )

size

Возвращает количество бит в объекте bitset.

size_t size() const;

Возвращаемое значение

Число битов , Nв bitset<N>.

Пример

// bitset_size.cpp
// compile with: /EHsc
#include <bitset>
#include <iostream>

int main()
{
    using namespace std;

    bitset<5> b1(6);
    size_t i;

    cout << "The set of bits in bitset<5> b1( 6 ) is: ( "<< b1 << " )"
         << endl;

    i = b1.size();

    cout << "The number of bits in bitset b1 is: " << i << "."
         << endl;
}
The set of bits in bitset<5> b1( 6 ) is: ( 00110 )
The number of bits in bitset b1 is: 5.

test

Проверяет, присвоено ли биту в указанной позиции в bitset значение 1.

bool test(size_t pos) const;

Параметры

pos
Позиция бита в тестируемом bitset значении.

Возвращаемое значение

true Значение , если бит, указанный позицией аргумента, имеет значение 1; falseв противном случае .

Замечания

Функция-член вызывает исключение out_of_range

to_string

Преобразует объект bitset в строковое представление.

template <class charT = char, class traits = char_traits<charT>, class Allocator = allocator<charT> >
   basic_string<charT, traits, Allocator> to_string(charT zero = charT('0'), charT one = charT('1')) const;

Возвращаемое значение

Строковый объект класса basic_string, где каждый бит в bitset наборе имеет соответствующий символ 1 и символ 0, если бит не задан.

Пример

// bitset_to_string.cpp
// compile with: /EHsc
#include <bitset>
#include <iostream>
#include <string>

int main( )
{
   using namespace std;

   bitset<5> b1 ( 7 );

   cout << "The ordered set of bits in the bitset<5> b1( 7 )"
        << "\n  that was generated by the number 7 is: ( "
        << b1 << " )" << endl;

   string s1;
   s1 =  b1.template to_string<char,
   char_traits<char>, allocator<char> >( );
   cout << "The string returned from the bitset b1"
        << "\n  by the member function to_string( ) is: "
        << s1 << "." << endl;
}
The ordered set of bits in the bitset<5> b1( 7 )
  that was generated by the number 7 is: ( 00111 )
The string returned from the bitset b1
  by the member function to_string( ) is: 00111.

to_ullong

unsigned long long Возвращает значение, содержащее те же биты, что и содержимое bitset объекта.

unsigned long long to_ullong() const;

Возвращаемое значение

Возвращает сумму битовых значений, которые находятся в битовой последовательности в виде unsigned long long. Это unsigned long long значение будет повторно создавать те же биты набора, если используется для инициализации bitset.

Исключения

overflow_error Создает объект, если бит в битовой последовательности имеет битовое значение, которое не может быть представлено как значение типаunsigned long long.

Замечания

Возвращает сумму битовых значений, которые находятся в битовой последовательности в виде unsigned long long.

to_ulong

bitset Преобразует объект в целое число, которое создаст последовательность битов, содержащихся, если используется для инициализацииbitset.

unsigned long to_ulong( ) const;

Возвращаемое значение

Целое число, которое создаст биты в bitset случае использования при инициализации объекта bitset.

Замечания

Применение функции-члена вернет целое число с той же последовательностью 1 и 0 цифр, что и в последовательности битов, содержащихся в.bitset

Функция-член создает overflow_error объект, если бит в битовой последовательности имеет битовое значение, которое не может быть представлено как значение типа unsigned long.

Пример

// bitset_to_ulong.cpp
// compile with: /EHsc
#include <bitset>
#include <iostream>

int main( )
{
   using namespace std;

   bitset<5> b1 ( 7 );

   cout << "The ordered set of bits in the bitset<5> b1( 7 )"
        << "\n  that was generated by the number 7 is: ( "
        << b1 << " )" << endl;

   unsigned long int i;
   i = b1.to_ulong( );
   cout << "The integer returned from the bitset b1,"
        << "\n  by the member function to_long( ), that"
        << "\n  generated the bits as a base two number is: "
        << i << "." << endl;
}
The ordered set of bits in the bitset<5> b1( 7 )
  that was generated by the number 7 is: ( 00111 )
The integer returned from the bitset b1,
  by the member function to_long( ), that
  generated the bits as a base two number is: 7.