bitset operator[] in C++ STL

bitset::operator[] is a built-in function in C++ STL which is used to assign value to any index of a bitset.

Syntax:

bitset_name[index] = value

Parameter: The parameter index specifies the position at which the value is to be assigned.



Return Value: The function returns the value to the bit at the index.

Below programs illustrate the bitset::operator[] function.

Program 1:

filter_none

edit
close

play_arrow

link
brightness_4
code

// CPP program to illustrate the
// bitset::operator[]
#include <bits/stdc++.h>
using namespace std;
  
int main()
{
    // Initialization of bitset
    // by zeros of size 6
    bitset<6> b;
  
    // initialises second index as 1
    b[2] = 1;
  
    // initialises fifth index as 1
    b[5] = 1;
  
    // prints the bitset
    cout << "The bitset after assigning values is: " << b;
    return 0;
}

chevron_right


Output:

The bitset after assigning values is: 100100

Program 2:

filter_none

edit
close

play_arrow

link
brightness_4
code

// CPP program to illustrate the
// bitset::operator[]
// assign value from a index
#include <bits/stdc++.h>
using namespace std;
  
int main()
{
    // Initialization of bitset
    // by zeros of size 6
    bitset<6> b;
  
    // initialises second index as 1
    b[2] = 1;
  
    // initialises fifth index as the same as b[2]
    b[3] = b[2];
  
    b[0] = b[5];
      
    // prints the bitset
    cout << "The bitset after assigning values is: " << b;
    return 0;
}

chevron_right


Output:

The bitset after assigning values is: 001100

Program 3:

filter_none

edit
close

play_arrow

link
brightness_4
code

// CPP program to illustrate the
// bitset::operator[]
// prints the value of bit at index
#include <bits/stdc++.h>
using namespace std;
  
int main()
{
    // Initialization of bitset
    // by zeros of size 6
    bitset<6> b;
  
    // initialises second index as 1
    b[2] = 1;
  
    // initialises fifth index as the same as b[2]
    b[3] = b[2];
  
    b[0] = b[5];
      
      
    cout << "The bit value at index 3 is " << b[3];
    return 0;
}

chevron_right


Output:

The bit value at index 3 is 1


My Personal Notes arrow_drop_up

The function of education is to teach one to think intensively and to think critically

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.




Article Tags :
Practice Tags :


Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.