Clase bitset

Describe un tipo de objeto que almacena una secuencia que consta de un número fijo de bits que proporcionan una manera compacta de mantener indicadores para un conjunto de elementos o condiciones. La clase bitset admite operaciones en objetos de tipo bitset que contienen una colección de bits y proporcionan acceso de tiempo constante a cada bit.

Sintaxis

template <size_t N>
class bitset

Parámetros

N
Especifica el número de bits del objeto bitset con un entero distinto de cero de tipo size_t que deben conocerse en tiempo de compilación.

Comentarios

A diferencia de la clase similar vector<bool> Class, la clase bitset no tiene iteradores y no es un contenedor de la biblioteca estándar de C++. También se distingue de vector<bool> en que es de un determinado tamaño específico que se fija en tiempo de compilación de acuerdo con el tamaño especificado por el parámetro de plantilla N cuando se declara bitset<N>.

Un bit se establece si su valor es 1 y se restablece si su valor es 0. Voltear o invertir un bit es cambiar su valor de 1 a 0 o de 0 a 1. Los bits N en un bitset están indexados por valores enteros de 0 a N - 1, donde 0 indexa la posición del primer bit y N -1, la posición del último bit.

Miembros

Constructores

Nombre Descripción
bitset Construye un objeto de clase bitset<N> e inicializa los bits a cero, hasta un valor especificado o hasta los valores obtenidos de los caracteres de una cadena.

Typedefs

Nombre Descripción
element_type Tipo sinónimo del tipo de datos bool y que se puede usar para hacer referencia a los bits de elemento en un bitset.

Functions

Nombre Descripción
all Comprueba todos los bits de este bitset para determinar si están establecidos en true.
any Función miembro que comprueba si cualquiera de los bits de la secuencia está establecido en 1.
count Función miembro que devuelve el número de bits establecidos en la secuencia de bits.
flip Invierte el valor de todos los bits de un bitset o de un solo bit en una posición especificada.
none Comprueba si no se ha establecido ningún bit en 1 en un objeto bitset.
reset Restablece todos los bits en un bitset en 0 o restablece un bit en una posición especificada en 0.
set Establece todos los bits en un bitset en 1 o establece un bit en una posición especificada en 1.
size Devuelve el número de bits de un objeto bitset.
test Comprueba si el bit de una posición especificada en un bitset está establecido en 1.
to_string Convierte un objeto bitset en una representación de cadena.
to_ullong Devuelve la suma de los valores de bits en el bitset como un unsigned long long.
to_ulong Convierte un objeto bitset en el unsigned long que generaría la secuencia de bits contenida si se usase para inicializar el bitset.

Clases

NOMBRE Descripción
reference Clase de proxy que proporciona referencias a los bits que contiene un bitset y que se usa para acceder y manipular los bits individuales como una clase del asistente para el operator[] de clase bitset.

Operadores

Nombre Descripción
operator!= Comprueba si hay desigualdad entre un bitset de destino y un bitset especificado.
operator&= Realiza una combinación bit a bit de los conjuntos de bits con la operación bit a bit "and" (&).
operator<< Desplaza los bits de un bitset a la izquierda un número especificado de posiciones y devuelve el resultado a un nuevo bitset.
operator<<= Desplaza los bits de un bitset a la izquierda un número especificado de posiciones y devuelve el resultado al bitset de destino.
operator== Comprueba si hay igualdad entre un bitset de destino y un bitset especificado.
operator>> Desplaza los bits de un bitset a la derecha un número especificado de posiciones y devuelve el resultado a un nuevo bitset.
operator>>= Desplaza los bits de un bitset a la derecha un número especificado de posiciones y devuelve el resultado al bitset de destino.
operator[] Devuelve una referencia a un bit en una posición especificada en un bitset si el bitset es modificable; en caso contrario, devuelve el valor del bit en esa posición.
operator^= Realiza una combinación bit a bit de los conjuntos de bits con la operación bit a bit "xor" (^).
operator|= Realiza una combinación bit a bit de los conjuntos de bits con la operación bit a bit "or" (|).
operator~ Invierte todos los bits en un bitset de destino y devuelve el resultado.

Estructuras

Nombre Descripción
hash

all

Comprueba todos los bits de este conjunto de bits para determinar si están establecidos en true.

bool all() const;

Valor devuelto

Devuelve true si todos los bits de este conjunto son true. Devuelve false si uno o más bits son false.

any

Comprueba si algún bit de la secuencia está establecido en 1.

bool any() const;

Valor devuelto

true si algún bit de este bitset se establece en 1; false si todos los bits son 0.

Ejemplo

// 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

Construye un objeto de clase bitset<N> e inicializa los bits a cero, hasta un valor especificado o hasta los valores obtenidos de los caracteres de una cadena.

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

Parámetros

val
El entero sin signo cuya representación de base dos se usa para inicializar los bits en el bitset que se está construyendo.

str
La cadena de ceros y unos que se usa para inicializar los valores de bits de bitset.

pos
La posición del carácter en la cadena, contando de izquierda a derecha y a partir de cero, que se usa para inicializar el primer bit en bitset.

count
El número de caracteres de la cadena que se usa para proporcionar los valores iniciales de los bits en bitset.

Zero
El carácter que se usa para representar un cero. El valor predeterminado es "0".

One
El carácter que se usa para representar un uno. El valor predeterminado es "1".

Comentarios

1) Crea un objeto de clase bitset<N> e inicializa todos los bits N en un valor predeterminado de cero.

2-3) Crea un objeto de clase bitset<N> e inicializa todos los bits del parámetro val.

4) Crea un objeto de clase bitset<N> e inicializa bits de los caracteres proporcionados en una cadena de ceros y unos. Si algún carácter de la cadena es distinto de 0 o 1, el constructor produce un objeto de clase invalid argument. Si la posición especificada ( pos) está más allá de la longitud de la cadena, el constructor produce un objeto de clase out_of_range. El constructor establece solo esos bits en la posición j en el bitset que tiene 1 como carácter de la cadena en la posición pos + j. De manera predeterminada, pos es 0.

5) Similar a 4), pero incluye otro parámetro, count, que especifica el número de bits a inicializar. Tiene dos parámetros opcionales, _Zero y _One, que indican qué carácter de str se tiene que interpretar para indicar un bit 0 y un bit 1, respectivamente.

6) Crea un objeto de clase bitset<N>, inicializando los bits N en valores que corresponden a los caracteres proporcionados en una cadena de caracteres de estilo C de ceros y unos. Llame al constructor sin convertir la cadena a un tipo de cadena, por ejemplo: bitset<5> b5("01011");

Ejemplo

// 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

Devuelve el número de bits establecidos en la secuencia de bits.

size_t count() const;

Valor devuelto

Número de bits establecidos en la secuencia de bits.

Ejemplo

// 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

Tipo sinónimo del tipo de datos bool y que se puede usar para hacer referencia a los bits de elemento en un bitset.

typedef bool element_type;

Ejemplo

// 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

Invierte el valor de todos los bits de un bitset o de un solo bit en una posición especificada.

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

Parámetros

pos
La posición del bit cuyo valor se va a invertir.

Valor devuelto

Una copia del bitset modificado para el que se ha invocado la función miembro.

Comentarios

La segunda función miembro produce una excepción out_of_range si la posición especificada como parámetro es mayor que el tamaño N del bitset<N> al que se ha invertido el bit.

Ejemplo

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

None

Comprueba si no se ha establecido ningún bit en 1 en un objeto bitset.

bool none() const;

Valor devuelto

true si no se ha establecido ningún bit en bitset en 1; false si se ha establecido al menos un bit en 1.

Ejemplo

// 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!=

Comprueba si hay desigualdad entre un conjunto de bits de destino y un conjunto de bits especificado.

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

Parámetros

right
bitset que va a compararse con el conjunto de bits de destino para comprobar si son iguales.

Valor devuelto

true si los conjuntos de bits son diferentes; false si son iguales.

Comentarios

Los conjuntos de bits deben tener el mismo tamaño.

Ejemplo

// 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&=

Realiza una combinación bit a bit de los conjuntos de bits con la operación bit a bit "and" (&).

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

Parámetros

right
El bitset que se va a combinar bit a bit con el conjunto de bits de destino.

Valor devuelto

Conjunto de bits de destino modificado resultante de la operación bit a bit "and" (&) con el bitset especificado como parámetro.

Comentarios

Dos bits combinados mediante el operador AND devuelven true si cada bit es True; en caso contrario, su combinación devuelve false.

Los dos conjuntos de bits deben tener el mismo tamaño.

Ejemplo

// 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<<

Desplaza los bits de un bitset a la izquierda un número especificado de posiciones y devuelve el resultado a un nuevo bitset.

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

Parámetros

pos
El número de posiciones a la izquierda que se desplazarán los bits en el bitset.

Valor devuelto

Conjunto de bits modificado con los bits que se han desplazado a la izquierda el número de posiciones requerido.

Comentarios

La función de operador miembro devuelve bitset(*this) <<= pos, donde <<= desplaza los bits de bitset a la izquierda un número especificado de posiciones y devuelve el resultado al bitset de destino.

Ejemplo

// 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<<=

Desplaza los bits de un bitset a la izquierda un número especificado de posiciones y devuelve el resultado al bitset de destino.

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

Parámetros

pos
El número de posiciones a la izquierda que se desplazarán los bits en el bitset.

Valor devuelto

El bitset de destino modificado de modo que los bits se hayan desplazado a la izquierda el número de posiciones requerido.

Comentarios

Si no existe ningún elemento para desplazar en la posición, la función pone el bit en un valor de 0.

Ejemplo

// 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==

Comprueba si hay igualdad entre un conjunto de bits de destino y un conjunto de bits especificado.

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

Parámetros

right
bitset que va a compararse con el conjunto de bits de destino para comprobar si son iguales.

Valor devuelto

true si los conjuntos de bits son iguales; false si son diferentes.

Comentarios

Los conjuntos de bits deben tener el mismo tamaño.

Ejemplo

// 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>>

Desplaza los bits de un bitset a la derecha un número especificado de posiciones y devuelve el resultado a un nuevo conjunto de bits.

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

Parámetros

pos
El número de posiciones a la derecha que se desplazarán los bits en el bitset.

Valor devuelto

Un nuevo conjunto de bits en que los bits se han desplazado a la derecha el número de posiciones requerido en relación con el bitset de destino.

Ejemplo

// 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>>=

Desplaza los bits de un bitset a la derecha un número especificado de posiciones y devuelve el resultado al bitset de destino.

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

Parámetros

pos
El número de posiciones a la derecha que se desplazarán los bits en el bitset.

Valor devuelto

bitset de destino modificado de modo que los bits se hayan desplazado a la derecha el número de posiciones requerido.

Comentarios

Si no existe ningún elemento para desplazar en la posición, la función pone el bit en un valor de 0.

Ejemplo

// 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[]

Devuelve una referencia a un bit en una posición especificada en un bitset si el bitset es modificable; en caso contrario, devuelve el valor del bit en esa posición.

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

Parámetros

pos
La posición que localiza el bit en el bitset.

Comentarios

Al definir _ITERATOR_DEBUG_LEVEL como 1 o 2 en la compilación, se producirá un error en tiempo de ejecución en el ejecutable si intenta obtener acceso a un elemento fuera de los límites del bitset. Para más información, vea Iteradores activados.

Ejemplo

// 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^=

Realiza una combinación bit a bit de los conjuntos de bits con la operación bit a bit "xor" (^).

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

Parámetros

right
El bitset que se va a combinar bit a bit con el conjunto de bits de destino.

Valor devuelto

Conjunto de bits de destino modificado resultante de la operación bit a bit "xor" (^) con el bitset especificado como parámetro.

Comentarios

Dos bits combinados mediante el operador exclusivo "xor"(^) devuelven true si al menos uno de los bits, pero no ambos, son true; de lo contrario, la combinación devuelve false.

Los conjuntos de bits deben tener el mismo tamaño.

Ejemplo

// 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|=

Combina dos conjuntos de bits mediante la operación bit a bit "or" (|).

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

Parámetros

right
El bitset que se va a combinar bit a bit con el bitset de destino.

Valor devuelto

Conjunto de bits de destino modificado resultante de la operación bit a bit "or" (|) con el bitset especificado como parámetro.

Comentarios

Dos bits combinados mediante el operador inclusivo OR devuelven true si al menos uno de los bits es true; si los dos bits son false, la combinación devuelve false.

Los conjuntos de bits deben tener el mismo tamaño.

Ejemplo

// 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~

Invierte todos los bits en un conjunto de bits de destino y devuelve el resultado.

bitset<N> operator~() const;

Valor devuelto

bitset con todos sus bits invertidos con respecto al bitset de destino.

Ejemplo

// 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

Clase de proxy que proporciona referencias a los bits que contiene un bitset y que se usa para acceder y manipular los bits individuales como una clase del asistente para el operator[] de clase 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();
};

Parámetros

val
El valor del objeto de tipo bool que se asignará a un bit en un bitset.

bitref
Una referencia con el formato x [ i ] al bit en la posición i en bitsetx.

Valor devuelto

Una referencia al bit en el bitset especificado por la posición del argumento para la primera, segunda y quinta función miembro de referencia de clase, y true o false, para reflejar el valor del bit modificado en bitset para la tercera y cuarta función miembro de referencia de clase.

Comentarios

La clase reference solo existe como una clase del asistente para el conjunto de bits bitsetoperator[]. La clase de miembro describe un objeto que puede tener acceso a un bit individual dentro de un bitset. Permita que b sea un objeto de tipo bool, x y y objetos de tipo bitset<N>, y i y j posiciones válidas dentro de este tipo de objeto. La notación x [i] hace referencia al bit en la posición i en el conjunto de bits x. Las funciones miembro de clase reference proporcionan, en orden, las siguientes operaciones:

Operación Definición
x[i] = b Almacena bool valor b en la posición de bit i en el conjunto de bits x.
x[i] = y[j] Almacena el valor del bit y[ j] en la posición del bit i en el conjunto de bits x.
b = ~ x[i] Almacena el valor volteado del bit x[ i] en boolb.
b = x[i] Almacena el valor del bit x[ i] en boolb.
x[i]. flip( ) Vuelve a almacenar el valor volteado del bit x [ i] en la posición del bit i en x.

Ejemplo

// 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

Restablece todos los bits en un bitset en 0 o restablece un bit en una posición especificada en 0.

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

Parámetros

pos
La posición del bit en el bitset que se restablecerá en 0.

Valor devuelto

Una copia del bitset para el que se ha invocado la función miembro.

Comentarios

La segunda función miembro produce una excepción out_of_range si la posición especificada es mayor que el tamaño del bitset.

Ejemplo

// 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

Establece todos los bits en un bitset en 1 o establece un bit en una posición especificada en 1.

bitset<N>& set();

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

Parámetros

pos
La posición del bit en el bitset al que se establecerá el valor asignado.

val
Valor que se asignará al bit en la posición especificada.

Valor devuelto

Una copia del bitset para el que se ha invocado la función miembro.

Comentarios

La segunda función miembro produce una excepción out_of_range si la posición especificada es mayor que el tamaño del bitset.

Ejemplo

// 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

Devuelve el número de bits de un objeto bitset.

size_t size() const;

Valor devuelto

Número de bits en N, en un bitset<N>.

Ejemplo

// 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

Comprueba si el bit de una posición especificada en un bitset está establecido en 1.

bool test(size_t pos) const;

Parámetros

pos
La posición del bit en el bitset al que se comprobará el valor.

Valor devuelto

true si el bit especificado por la posición del argumento está establecido en 1; de lo contrario, false.

Comentarios

La función miembro produce un out_of_range.

to_string

Convierte un objeto bitset en una representación de cadena.

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;

Valor devuelto

Objeto de cadena de la clase basic_string, donde cada bit establecido en bitset tiene un carácter correspondiente de 1 y un carácter de 0 si el bit no está establecido.

Ejemplo

// 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

Devuelve un valor unsigned long long que contiene los mismos bits establecidos como contenido del objeto bitset.

unsigned long long to_ullong() const;

Valor devuelto

Devuelve la suma de los valores de bits que se encuentran en la secuencia de bits como unsigned long long. Este unsigned long long volverá a crear los mismos bits establecidos si se utiliza para inicializar un bitset.

Excepciones

Produce un objeto overflow_error si cualquier bit de la secuencia de bits tiene un valor de bit que no se puede representar como un valor de tipo unsigned long long.

Comentarios

Devuelve la suma de los valores de bits que se encuentran en la secuencia de bits como unsigned long long.

to_ulong

Convierte un objeto bitset en el entero que generaría la secuencia de bits contenida si se usase para inicializar el bitset.

unsigned long to_ulong( ) const;

Valor devuelto

Entero que generaría los bits en un bitset si se usa en la inicialización de bitset.

Comentarios

La aplicación de la función miembro devolvería el entero que tiene la misma secuencia de 1 y 0 dígitos que se encuentra en secuencia de bits contenidos en bitset.

La función miembro produce un objeto overflow_error si cualquier bit de la secuencia de bits tiene un valor de bit que no se puede representar como un valor de tipo unsigned long.

Ejemplo

// 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.