bitset::set()是C++中的內置 STL,可將位設置為特定索引處的給定值。如果未傳遞任何參數,則將所有位設置為1。如果僅傳遞單個參數,則將該特定索引處的位設置為1。
用法:
set(int index, bool val)
參數:該函數接受以下兩個參數:
- index –該參數指定必須設置該位的位置。該參數是可選的。
- val –此參數指定一個布爾值,必須在索引處下注。該參數是可選的。
如果未傳遞任何參數,則將所有位設置為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。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。