C++ Bitset Library - operator[] Function



Description

The C++ function std::bitset::operator[] returns the reference of bit at position pos.

Declaration

Following is the declaration for std::bitset::operator[] function form std::bitset header.

C++98

reference operator[] (size_t pos);

Parameters

pos − Position of the bit whose value is accessed.

Return value

Returns an object of type bitset::reference, which allows writing to the requested bit.

Exceptions

If pos is not valid then this method causes undefined behavior. Otherwise if exception occurs all object remains in valid state.

Example

The following example shows the usage of std::bitset::operator[] function.

#include <iostream>
#include <bitset>

using namespace std;

int main(void) {

   bitset<4> b;

   cout << "Initial value of bitset = " << b << endl;

   b[1] = 1;
   b[3] = 1;

   cout << "Value of bitset after setting few bits = " << b << endl;

   return 0;
}

Let us compile and run the above program, this will produce the following result −

Initial value of bitset = 0000
Value of bitset after setting few bits = 1010
bitset.htm
Advertisements