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


C++ bitset set()用法及代码示例


bitset::set()是C++中的内置 STL,可将位设置为特定索引处的给定值。如果未传递任何参数,则将所有位设置为1。如果仅传递单个参数,则将该特定索引处的位设置为1。

用法:

set(int index, bool val) 

参数:该函数接受以下两个参数:


  1. index –该参数指定必须设置该位的位置。该参数是可选的。
  2. val –此参数指定一个布尔值,必须在索引处下注。该参数是可选的。
  3. 如果未传递任何参数,则将所有位设置为1。如果仅传递单个参数,则将其设置为该索引的位。

返回值:该函数不返回任何内容。

下面的程序演示了bitset::set()函数。

示例1:

// CPP program to illustrate the 
// bitset::set() function 
// when parameter is not passed 
  
#include <bits/stdc++.h> 
using namespace std; 
  
int main() 
{ 
    // Initialization of bitset 
    bitset<4> b1(string("1100")); 
    bitset<6> b2(string("100100")); 
  
    // Function that resets all bits 
    cout << "Before applying set() function: "
         << b1 << endl; 
  
    b1.set(); 
    cout << "After applying set() function: "
         << b1 << endl; 
  
    // Function that resets all bits 
    cout << "Before applying set() function: "
         << b2 << endl; 
  
    b2.set(); 
    cout << "After applying set() function: "
         << b2 << endl; 
  
    return 0; 
}
输出:
Before applying set() function: 1100
After applying set() function: 1111
Before applying set() function: 100100
After applying set() function: 111111

示例2:

// CPP program to illustrate the 
// bitset::set() function 
// when parameter is passed 
  
#include <bits/stdc++.h> 
using namespace std; 
  
int main() 
{ 
    // Initialization of bitset 
    bitset<4> b1(string("1100")); 
    bitset<6> b2(string("100100")); 
  
    // Function that resets all bits 
    cout << "Before applying set() function: "
         << b1 << endl; 
  
    // single parameter is passed 
    b1.set(1); 
    cout << "After applying set(1) function: "
         << b1 << endl; 
  
    // Function that resets all bits 
    cout << "Before applying set() function: "
         << b2 << endl; 
  
    // both parameters is passed 
    b2.set(2, 0); 
    b2.set(4, 1); 
    cout << "After applying set(2, 0) and"
         << " set(4, 1) function: " << b2 << endl; 
  
    return 0; 
}
输出:
Before applying set() function: 1100
After applying set(1) function: 1110
Before applying set() function: 100100
After applying set(2, 0) and set(4, 1) function: 110000

注:本文由纯净天空筛选整理自 bitset set() function in C++ STL。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。