📜  C++ STL中的bitset set()函数

📅  最后修改于: 2021-05-30 11:58:49             🧑  作者: Mango

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

句法:

set(int index, bool val) 

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

  1. index –该参数指定必须设置该位的位置。该参数是可选的。
  2. val –此参数指定一个布尔值,必须在索引处下注。该参数是可选的。

    如果未传递任何参数,则将所有位设置为1。如果仅传递单个参数,则将其设置为该索引的位。

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

下面的程序说明了bitset :: set()函数。

程序1:

// CPP program to illustrate the
// bitset::set() function
// when parameter is not passed
  
#include 
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 
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