Skip to content
Related Articles

Related Articles

bitset operator[] in C++ STL
  • Last Updated : 12 Nov, 2020

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

Syntax:  

bitset_operator[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:  

C++




// C++ 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;
}
Output: 
The bitset after assigning values is: 100100






 

Program 2: 

C++




// C++ 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;
}
Output: 
The bitset after assigning values is: 001100






 

Program 3: 

C++




// C++ 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;
}
Output: 
The bit value at index 3 is 1






 

Want to learn from the best curated videos and practice problems, check out the C++ Foundation Course for Basic to Advanced C++ and C++ STL Course for foundation plus STL.  To complete your preparation from learning a language to DS Algo and many more,  please refer Complete Interview Preparation Course.
My Personal Notes arrow_drop_up
Recommended Articles
Page :