当前位置: 首页>>代码示例 >>用法及示例精选 >>正文


C++ bitset operator[]用法及代码示例


bitset::operator []是C++ STL中的内置函数,用于将值分配给位集的任何索引。

用法:

bitset_name[index] = value

参数:参数索引指定要分配值的位置。



返回值:该函数将值返回到索引处的位。

以下示例程序旨在说明bitset::operator []函数。

程序1:

// 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; 
}
输出:
The bitset after assigning values is:100100

程序2:

// 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; 
}
输出:
The bitset after assigning values is:001100

程序3:

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



相关用法


注:本文由纯净天空筛选整理自gopaldave大神的英文原创作品 bitset operator[] in C++ STL。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。