C++ Standard Library C++ STL Library

C++ <bitset> - set() Function



The C++ bitset::set function is used to set (to one) all bits of the bitset. Along with this, it is also used to modify the bit at specified position.

Syntax

//set all bits
bitset& set();

//set single bit	
bitset& set (size_t pos, bool val = true);
//set all bits
bitset& set() noexcept;

//set single bit	
bitset& set (size_t pos, bool val = true);

Parameters

pos Specify position of the bit whose value is modified.
val Specify the value to store in the bit.

Return Value

*this

Exception

Version 1: never throws exception. Version 2: throws out_of_range, if specified position is not a valid bit position.

Example:

The example below shows the usage of bitset::set function.

#include <iostream>
#include <bitset>
using namespace std;
 
int main (){
  bitset<4> bset("1100");
  
  cout<<"1. bset is: "<<bset<<"\n";

  //set all bits
  bset.set();
  cout<<"2. bset is: "<<bset<<"\n";

  //set bit at specified position
  bset.set(2, 0);
  cout<<"3. bset is: "<<bset<<"\n";

  //set bit at specified position
  bset.set(1, false);
  cout<<"4. bset is: "<<bset<<"\n";

  //set bit at position=1 to true
  bset.set(1);
  cout<<"5. bset is: "<<bset<<"\n";

  return 0;
}

The output of the above code will be:

1. bset is: 1100
2. bset is: 1111
3. bset is: 1011
4. bset is: 1001
5. bset is: 1011

❮ C++ <bitset> Library