C++ Standard Library C++ STL Library

C++ <bitset> - operator[]() Function



The C++ bitset::operator[] function returns the value (or a reference) to the bit at the specified position.

Syntax

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

Parameters

pos Specify position of the bit whose value is accessed.

Return Value

The bit at specified position.

Exception

If specified position is not valid then it causes undefined behavior. Otherwise if an exception occurs, the bitset is left in a valid state.

Example:

In the example below, the bitset::operator[] function is used to access the bits of the given bitset.

#include <iostream>
#include <bitset>
using namespace std;
 
int main (){
  bitset<6> bset("100000");

  cout<<"bset is: "<<bset;
  
  //reference version
  bset[0] = 1;
  bset[1] = 1;

  cout<<"\nbset is: "<<bset;

  return 0;
}

The output of the above code will be:

bset is: 100000
bset is: 100011

Example:

In the example below, the bool version of operator[] function is used to access the bits of the given bitset.

#include <iostream>
#include <bitset>
using namespace std;
 
int main (){
  bitset<3> bset("100");

  cout<<"bset is: "<<bset;
  
  //bool version
  cout<<"\nbset[0] = "<<bset[0];
  cout<<"\nbset[1] = "<<bset[1];
  cout<<"\nbset[2] = "<<bset[2];

  return 0;
}

The output of the above code will be:

bset is: 100
bset[0] = 0
bset[1] = 0
bset[2] = 1

❮ C++ <bitset> Library