bitset classe

Descreve um tipo de objeto que armazena uma sequência composta por um número fixo de bits que fornece uma forma compacta de manter flags para um conjunto de itens ou condições. A bitset classe suporta operações sobre objetos de conjunto de bits do tipo que contêm uma coleção de bits e fornecem acesso em tempo constante a cada bit.

Syntax

template <size_t N>
class bitset

Parameters

N
Especifica o número de bits no bitset objeto com um inteiro não nulo do tipo size_t que deve ser conhecido em tempo de compilação.

Remarks

Ao contrário da Classe semelhantevector<bool>, a bitset classe não tem iteradores e não é um contentor de Biblioteca Padrão em C++. Também difere por vector<bool> ter um tamanho específico que é fixo em tempo de compilação de acordo com o tamanho especificado pelo parâmetro N template quando o bitset<N> é declarado.

Um bit é definido se o seu valor for 1 e reiniciado se o seu valor for 0. Inverter ou inverter um bit é mudar o seu valor de 1 para 0 ou de 0 para 1. Os N bits em a bitset são indexados por valores inteiros de 0 a N - 1, onde 0 indica a posição do primeiro bit e N - 1 a posição final do bit.

Members

Constructors

Name Description
bitset Constrói um objeto de classe bitset<N> e inicializa os bits a zero, a um valor especificado, ou a valores obtidos a partir de caracteres numa cadeia.

Typedefs (definições de tipos)

Name Description
element_type Um tipo que é sinónimo do tipo bool de dados e pode ser usado para referenciar bits de elemento num bitset.

Funções

Name Description
all Testa todos os bits disto bitset para determinar se estão todos definidos para true.
any A função membro testa se algum bit da sequência está definido como 1.
count A função membro devolve o número de bits definidos na sequência de bits.
flip Inverte o valor de todos os bits em a bitset ou inverte um único bit numa posição especificada.
none Testa se nenhum bit tiver sido definido como 1 num bitset objeto.
reset Reinicia todos os bits de a bitset para 0 ou reinicia um bit numa posição especificada para 0.
set Define todos os bits de a bitset para 1 ou define um bit numa posição especificada para 1.
size Devolve o número de bits num bitset objeto.
test Testa se o bit numa posição especificada em a bitset está definido como 1.
to_string Converte um bitset objeto numa representação de cadeia.
to_ullong Devolve a soma dos valores de bits no bitset como um unsigned long long.
to_ulong Converte um bitset objeto para o unsigned long que geraria a sequência de bits contidos se usado para inicializar o bitset.

Aulas

Name Description
reference Uma classe proxy que fornece referências a bits contidos em a bitset e que é usada para aceder e manipular os bits individuais como uma classe auxiliar para a operator[] classe bitsetde .

Operadores

Name Description
operator!= Testa um alvo bitset para desigualdade com um especificado bitset.
operator&= Faz uma combinação bit a bit de conjuntos com a operação bit a bit "e" (&).
operator<< Desloca os bits de a bitset para a esquerda um número especificado de posições e devolve o resultado a um novo bitset.
operator<<= Desloca os bits de a bitset para a esquerda um número especificado de posições e devolve o resultado ao alvo bitset.
operator== Testa um alvo bitset para igualdade com um especificado bitset.
operator>> Desloca os bits de a bitset para a direita um número especificado de posições e devolve o resultado a um novo bitset.
operator>>= Desloca os bits em a bitset para a direita um número especificado de posições e devolve o resultado ao alvo bitset.
operator[] Devolve uma referência a um bit numa posição especificada em a bitset se for bitset modificável; caso contrário, devolve o valor do bit nessa posição.
operador^= Faz uma combinação bit a bit de conjuntos com a operação bit a bit "xor" (^).
operator|= Faz uma combinação bit a bit de conjuntos com a operação bit a bit "ou" (|).
operator~ Inverte todos os bits de um alvo bitset e devolve o resultado.

Structures

Name Description
hash

all

Testa todos os bits deste conjunto para determinar se estão todos definidos como verdadeiros.

bool all() const;

Valor de retorno

Retorna true se todos os bits deste conjunto forem verdadeiros. Retorna false se um ou mais bits forem falsos.

any

Testa se algum bit da sequência está definido como 1.

bool any() const;

Valor de retorno

true se qualquer bit nisto bitset for definido como 1; false se todos os bits forem 0.

Example

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

Constrói um objeto de classe bitset<N> e inicializa os bits a zero, ou a algum valor especificado, ou a valores obtidos a partir de caracteres numa cadeia.

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

Parameters

val
O inteiro sem sinal cuja representação em base dois é usada para inicializar os bits no bitset ser construído.

str
A cadeia de zeros e uns usada para inicializar os valores dos bitset bits.

pos
A posição do carácter na cadeia, contando da esquerda para a direita e começando com zero, é usada para inicializar o primeiro bit no bitset.

count
O número de caracteres na cadeia usada para fornecer valores iniciais para os bits do bitset.

Zero
O carácter usado para representar um zero. O padrão é '0'.

One
O carácter que é usado para representar um um. O padrão é '1'.

Remarks

1) Constrói um objeto de classe bitset<N> e inicializa todos os N bits num valor padrão de zero.

2-3) Constrói um objeto de classe bitset<N> e inicializa os bits a partir do val parâmetro.

4) Constrói um objeto de classe bitset<N> e inicializa bits a partir dos caracteres fornecidos numa sequência de zeros e uns. Se quaisquer caracteres da cadeia forem diferentes de 0 ou 1, o construtor lança um objeto de classe invalid argument. Se a posição especificada (pos) for superior ao comprimento da cadeia, então o construtor lança um objeto de classe out_of_range. O construtor define apenas os bits na posição j em para os bitset quais o carácter na cadeia na posição pos + j é 1. Por defeito, pos é 0.

5) Semelhante a 4) mas inclui outro parâmetro, count, que especifica o número de bits a inicializar. Tem dois parâmetros opcionais, _Zero e _One, que indicam que carácter em str deve ser interpretado como significando um bit 0 e um bit 1, respetivamente.

6) Constrói um objeto de classe bitset<N>, inicializando os N bits para valores que correspondem aos caracteres fornecidos numa cadeia de caracteres ao estilo C de zeros e uns. Chama o construtor sem fundir a cadeia num tipo de cadeia, por exemplo: bitset<5> b5("01011");

Example

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

Devolve o número de bits definidos na sequência de bits.

size_t count() const;

Valor de retorno

O número de bits definidos na sequência de bits.

Example

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

Um tipo que é sinónimo do tipo bool de dados e pode ser usado para referenciar bits de elemento num bitset.

typedef bool element_type;

Example

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

Inverte o valor de todos os bits em a bitset ou inverte um único bit numa posição especificada.

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

Parameters

pos
A posição do bit cujo valor deve ser invertido.

Valor de retorno

Uma cópia do modificado bitset para o qual a função membro foi invocada.

Remarks

A função do segundo membro lança uma out_of_range exceção se a posição especificada como parâmetro for maior do que o tamanho N do bitset<N> cujo bit foi invertido.

Example

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

Testa se nenhum bit tiver sido definido como 1 num bitset objeto.

bool none() const;

Valor de retorno

true se nenhum bit no bitset foi definido como 1; false se pelo menos um bit foi definido como 1.

Example

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

Testa um conjunto de bits-alvo para desigualdade com um conjunto de bits especificado.

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

Parameters

right
O bitset que deve ser comparado com o conjunto de bits alvo para a desigualdade.

Valor de retorno

true se os conjuntos de bits forem diferentes; false se forem iguais.

Remarks

Os conjuntos de bits devem ter o mesmo tamanho.

Example

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

Faz uma combinação bit a bit de conjuntos com a operação bit a bit "e" (&).

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

Parameters

right
Ou seja bitset , deve ser combinado bit a bit com o conjunto de bits alvo.

Valor de retorno

O conjunto de bits-alvo modificado que resulta da operação bit a bit "and" (&) com o bitset especificado como parâmetro.

Remarks

Dois bits combinados pelo AND operador retornam true se cada bit for verdadeiro; caso contrário, a sua combinação retorna false.

Os dois conjuntos de bits devem ter o mesmo tamanho.

Example

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

Desloca os bits de a bitset para a esquerda um número especificado de posições e devolve o resultado a um novo bitset.

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

Parameters

pos
O número de posições à esquerda em que os bits bitset no devem ser deslocados.

Valor de retorno

O conjunto de bits modificado com os bits deslocados para a esquerda o número necessário de posições.

Remarks

A função operadora membro devolve bitset(*this) <<= pos onde <<= desloca os bits para bitset a esquerda um número especificado de posições e devolve o resultado ao alvo bitset.

Example

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

Desloca os bits de a bitset para a esquerda um número especificado de posições e devolve o resultado ao alvo bitset.

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

Parameters

pos
O número de posições à esquerda, os bits no bitset devem ser deslocados.

Valor de retorno

O alvo bitset foi modificado para que os bits tenham sido deslocados para a esquerda o número de posições necessário.

Remarks

Se não existir elemento para se deslocar para a posição, a função limpa o bit para um valor de 0.

Example

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

Testa um conjunto de bits alvo para igualdade com um conjunto de bits especificado.

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

Parameters

right
Ou seja bitset , deve ser comparado com o conjunto de bits alvo para igualdade.

Valor de retorno

true se os conjuntos de bits forem iguais; false se forem diferentes.

Remarks

Os conjuntos de bits devem ter o mesmo tamanho.

Example

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

Desloca os bits para bitset a direita um número especificado de posições e devolve o resultado a um novo conjunto de bits.

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

Parameters

pos
O número de posições à direita, os bits bitset no devem ser deslocados.

Valor de retorno

Um novo conjunto de bits onde os bits foram deslocados para a direita do número necessário de posições em relação ao alvo bitset.

Example

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

Desloca os bits em a bitset para a direita um número especificado de posições e devolve o resultado ao alvo bitset.

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

Parameters

pos
O número de posições à direita, os bits bitset no devem ser deslocados.

Valor de retorno

O alvo bitset foi modificado para que os bits tenham sido deslocados para a direita do número necessário de posições.

Remarks

Se não existir elemento para se deslocar para a posição, a função limpa o bit para um valor de 0.

Example

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

Devolve uma referência a um bit numa posição especificada em a bitset se for bitset modificável; caso contrário, devolve o valor do bit nessa posição.

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

Parameters

pos
A posição que localiza o bit dentro do bitset.

Remarks

Quando defines _ITERATOR_DEBUG_LEVEL como 1 ou 2 na tua build, ocorrerá um erro de execução no executável se tentares aceder a um elemento fora dos limites do bitset. Para obter mais informações, consulte Iteradores verificados.

Example

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

Faz uma combinação bit a bit de conjuntos com a operação bit a bit "xor" (^).

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

Parameters

right
Ou seja bitset , deve ser combinado bit a bit com o conjunto de bits alvo.

Valor de retorno

O conjunto de bits-alvo modificado que resulta da operação bit a bit "xor" (^) com o bitset especificado como parâmetro.

Remarks

Dois bits combinados pelo operador bit a bit "xor" (^) retornam true se pelo menos um, mas não ambos, dos bits forem true; caso contrário, a sua combinação retorna false.

Os conjuntos de bits devem ter o mesmo tamanho.

Example

// 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 dois conjuntos de bits usando a operação bit a bit "ou" (|).

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

Parameters

right
Ou bitset seja, deve ser combinado bit a bit com o alvo bitset.

Valor de retorno

O conjunto de bits-alvo modificado que resulta da operação bit a bit "ou" (|) com o bitset especificado como parâmetro.

Remarks

Dois bits combinados pelo operador inclusivo OR retornam true se pelo menos um dos bits for true; se ambos os bits são false, a sua combinação retorna false.

Os conjuntos de bits devem ter o mesmo tamanho.

Example

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

Inverte todos os bits de um conjunto de bits alvo e devolve o resultado.

bitset<N> operator~() const;

Valor de retorno

Com bitset todos os seus bits invertidos em relação ao alvo bitset.

Example

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

Uma classe proxy que fornece referências a bits contidos em a bitset e que é usada para aceder e manipular os bits individuais como uma classe auxiliar para a operator[] classe bitsetde .

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

Parameters

val
O valor do objeto do tipo bool a ser atribuído a um bit num bitset.

bitref
Uma referência da forma x [ i ] ao bit na posição i em bitsetx.

Valor de retorno

Uma referência ao bit na bitset posição especificada pela posição do argumento para as funções de primeiro, segundo e quinto membros da referência de classe, e true ou false, para refletir o valor do bit modificado em para bitset as funções do terceiro e quarto membro da referência de classe.

Remarks

A classe reference existe apenas como classe auxiliar para o bitsetoperator[]. A classe membro descreve um objeto que pode aceder a um bit individual dentro de um bitset. Seja b um objeto de tipo bool, x e y objetos de tipo bitset<N>, e ij e posições válidas dentro de tal objeto. A notação x [i] faz referência ao bit na posição i no conjunto xde bits . As funções membros da classe reference fornecem, por ordem, as seguintes operações:

Operação Definition
x[i] = b Armazena bool valor b na posição i de bits no conjunto xde bits.
x[i] = y [j] Armazena o valor do bit y[ j] na posição i do bit no conjunto xde bits .
b = ~ x[i] Armazena o valor invertido do bit x[ i] em boolb.
b = x[i] Armazena o valor do bit x[ i] em boolb.
x[i]. flip( ) Armazena o valor invertido do bit x[ i] de volta na posição i do bit em x.

Example

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

Reinicia todos os bits de a bitset para 0 ou reinicia um bit numa posição especificada para 0.

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

Parameters

pos
A posição do bit no bitset a ser reiniciada para 0.

Valor de retorno

Uma cópia do bitset para o qual a função membro foi invocada.

Remarks

A função do segundo elemento lança uma out_of_range exceção se a posição especificada for maior do que o tamanho do bitset.

Example

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

Define todos os bits de a bitset para 1 ou define um bit numa posição especificada para 1.

bitset<N>& set();

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

Parameters

pos
A posição do bit no bitset a definir define o valor atribuído.

val
O valor a atribuir ao bit na posição especificada.

Valor de retorno

Uma cópia do bitset para o qual a função membro foi invocada.

Remarks

A função do segundo elemento lança uma out_of_range exceção se a posição especificada for maior do que o tamanho do bitset.

Example

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

Devolve o número de bits num bitset objeto.

size_t size() const;

Valor de retorno

O número de bits, N, num bitset<N>.

Example

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

Testa se o bit numa posição especificada em a bitset está definido como 1.

bool test(size_t pos) const;

Parameters

pos
A posição do bit no bitset a ser testado quanto ao seu valor.

Valor de retorno

true se o bit especificado pela posição do argumento for definido como 1; caso contrário, false.

Remarks

A função membro lança um out_of_range

to_string

Converte um bitset objeto numa representação de cadeia.

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 de retorno

Um objeto string da classe basic_string, onde cada conjunto de bits em tem bitset um carácter correspondente de 1, e um carácter de 0 se o bit estiver desdefinido.

Example

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

Devolve um unsigned long long valor que contém o mesmo conjunto de bits que o conteúdo do bitset objeto.

unsigned long long to_ullong() const;

Valor de retorno

Devolve a soma dos valores de bits que pertencem à sequência de bits como um unsigned long long. Este unsigned long long valor recriaria os mesmos bits de conjunto se fosse usado para inicializar um bitset.

Exceptions

Lança um overflow_error objeto se qualquer bit da sequência de bits tiver um valor de bit que não pode ser representado como um valor do tipo unsigned long long.

Remarks

Devolve a soma dos valores de bits que pertencem à sequência de bits como um unsigned long long.

to_ulong

Converte um bitset objeto para o inteiro que geraria a sequência de bits contidos se usado para inicializar o bitset.

unsigned long to_ulong( ) const;

Valor de retorno

Um inteiro que geraria os bits em a bitset se for usado na inicialização do bitset.

Remarks

Aplicar a função membro retornaria o inteiro que tem a mesma sequência de dígitos 1 e 0 que se encontra na sequência de bits contidos no bitset.

A função membro lança um overflow_error objeto se qualquer bit da sequência de bits tiver um valor de bit que não pode ser representado como um valor do tipo unsigned long.

Example

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