名稱空間
變體
操作

std::bitset

來自 cppreference.com
< cpp‎ | 工具
 
 
 
 
定義於標頭檔案 <bitset>
template< std::size_t N >
class bitset;

類模板 bitset 表示一個固定大小的 N 位序列。位集可以透過標準邏輯運算子進行操作,並可以與字串和整數相互轉換。為了字串表示和移位操作的方向命名,該序列被認為其最低索引元素在**右側**,如同整數的二進位制表示一樣。

bitset 滿足 CopyConstructibleCopyAssignable 的要求。

std::bitset 的所有成員函式都是 constexpr:可以在常量表達式的求值中建立和使用 std::bitset 物件。

(C++23 起)

目錄

[編輯] 模板引數

N - 要分配儲存的位數

[編輯] 成員型別

表示位引用的代理類
(類)

[編輯] 成員函式

構造位集
(公共成員函式) [編輯]
(在 C++20 中移除)
比較內容
(公共成員函式) [編輯]
元素訪問
訪問特定位
(公共成員函式) [編輯]
訪問特定位
(公共成員函式) [編輯]
檢查所有、任何或沒有位被設定為 true
(公共成員函式) [編輯]
返回被設定為 true 的位數
(公共成員函式) [編輯]
容量
返回位集持有的位數
(公共成員函式) [編輯]
修改器
執行二進位制 AND、OR、XOR 和 NOT
(公共成員函式) [編輯]
執行二進位制左移和右移
(公共成員函式) [編輯]
將位設定為 true 或給定值
(公共成員函式) [編輯]
將位設定為 false
(公共成員函式) [編輯]
切換位的值
(公共成員函式) [編輯]
轉換
返回資料的字串表示
(公共成員函式) [編輯]
返回資料的 unsigned long 整型表示
(公共成員函式) [編輯]
(C++11)
返回資料的 unsigned long long 整型表示
(公共成員函式) [編輯]

[編輯] 非成員函式

對位集執行二進位制邏輯操作
(函式模板) [編輯]
執行位集的流輸入和輸出
(函式模板) [編輯]

[編輯] 輔助類

std::bitset 的雜湊支援
(類模板特化) [編輯]

[編輯] 注意

如果位集的大小在編譯時未知,或者需要在執行時改變其大小,則可以使用動態型別,例如 std::vector<bool>boost::dynamic_bitset<>

特性測試 標準 特性
__cpp_lib_constexpr_bitset 202207L (C++23) 更 constexpr 的 std::bitset
__cpp_lib_bitset 202306L (C++26) std::bitsetstd::string_view 的介面

[編輯] 示例

#include <bitset>
#include <cassert>
#include <cstddef>
#include <iostream>
 
int main()
{
    typedef std::size_t length_t, position_t; // the hints
 
    // constructors:
    constexpr std::bitset<4> b1;
    constexpr std::bitset<4> b2{0xA}; // == 0B1010
    std::bitset<4> b3{"0011"}; // can also be constexpr since C++23
    std::bitset<8> b4{"ABBA", length_t(4), /*0:*/'A', /*1:*/'B'}; // == 0B0000'0110
 
    // bitsets can be printed out to a stream:
    std::cout << "b1:" << b1 << "; b2:" << b2 << "; b3:" << b3 << "; b4:" << b4 << '\n';
 
    // bitset supports bitwise operations:
    b3 |= 0b0100; assert(b3 == 0b0111);
    b3 &= 0b0011; assert(b3 == 0b0011);
    b3 ^= std::bitset<4>{0b1100}; assert(b3 == 0b1111);
 
    // operations on the whole set:
    b3.reset(); assert(b3 == 0);
    b3.set(); assert(b3 == 0b1111);
    assert(b3.all() && b3.any() && !b3.none());
    b3.flip(); assert(b3 == 0);
 
    // operations on individual bits:
    b3.set(position_t(1), true); assert(b3 == 0b0010);
    b3.set(position_t(1), false); assert(b3 == 0);
    b3.flip(position_t(2)); assert(b3 == 0b0100);
    b3.reset(position_t(2)); assert(b3 == 0);
 
    // subscript operator[] is supported:
    b3[2] = true; assert(true == b3[2]);
 
    // other operations:
    assert(b3.count() == 1);
    assert(b3.size() == 4);
    assert(b3.to_ullong() == 0b0100ULL);
    assert(b3.to_string() == "0100");
}

輸出

b1:0000; b2:1010; b3:0011; b4:00000110

[編輯] 另請參閱

節省空間的動態位集
(類模板特化) [編輯]
位操作 (C++20) 用於訪問、操作和處理單個位和位序列的工具