C++ bitset 的一些有趣事實?


C++ 程式語言在 C++ 標準模板庫中定義了一個名為 bitset 的容器。這個 bitset 容器用於在位級別操作元素,即變數的每個位,也就是給定值的二進位制轉換。

1. Bitset 就像一個字串 - Bitset 是一個位容器(只有 0 和 1 是有效的)。您可以建立任何一組位,由 bitset 的起始索引值和要考慮的元素數量指定,即您可以建立一個包含 2 個元素的 bitset,從 bitset 的索引 1 開始,並將其附加到 bitset 的末尾。

例如 - 我們需要從位字串 01001110 的索引值 2 開始填充 4 個元素。此 bitset 將獲取元素0011,這些元素將附加到 bitset 的末尾。因此,透過這種方法定義的 8 位 bitset 的值為00000011

示例

 現場演示

#include <bitset>
#include <string>
#include <iostream>
int main() {
   std::string bit_string = "10010110";
   std::bitset<8> b1(bit_string, 1 , 4);
   std::cout << b1 << '\n' ;
   return 0;
}

輸出

00000010

2. 從字串構造 Bitset - 如果您有一個字串,其中只有兩種型別的用於建立的值。您可以將此字串轉換為一個 bitset,該 bitset 將值視為其各自的 0/1 表示。

讓我們舉個例子來更好地理解這個概念,

我們有一個字串“xyxxyyx”,從中我們可以建立一個與陣列長度相同的 bitset,其中 x=0,y=1。建立的 bitset 為0100110

庫中定義了一個建構函式來執行此任務 -

bitset(str, offSet, size, zeroVal , oneVal) ;

這是一個用於建立 bitset 的建構函式。讓我們深入瞭解建構函式,並學習建構函式的每個引數傳達了什麼。

str - 用於建立 bitset 的字串。

offSet - 字串的字串索引。

size - 要建立的 bitset 的大小。

zeroVal - 將被視為 0 的字串值

oneVal - 將被視為 1 的字串值]

示例

 現場演示

#include <bitset>
#include <string>
#include <iostream>
using namespace std;
int main() {
   string bitstr = "xyxxyyyx";
   bitset<8> bits(bitstr, 0, bitstr.size(), 'x', 'y');
   cout <<"The bitset is : "<< bits << '\n';
}

輸出

The bitset is: 01001110

3. 將 bitset 轉換為字串 - 在 bitset 中,有一個函式可以將 bitset 轉換為字串。函式to_string()用於將 bitset 的值儲存到字串中。字串的長度與 bitset 的長度相同。

將 bitset 的元素儲存到字串中的順序與 bitset 順序相同,即 bitset 的第一個元素是字串的第一個元素。

01010100 的字串轉換是“01010100”。

您可以透過在方法的引數列表中指定來用任何字母替換 0 和 1。這只是我們在 bitset 構造時所學內容的反向操作。

示例

 現場演示

#include <iostream>
#include <bitset>
using namespace std;
int main() {
   bitset<8> b(19);
   cout<<"The value of the bitset is : "<<b<<endl;
   cout<<"The string conversion of the bitset is : "<<b.to_string()<<endl;
   cout<<"The string conversion by replacing 0 with T and 1 with P is : ";
   cout<< b.to_string('T', 'P')<<endl;
}

輸出

The value of bitset is : 00010011
The string conversion of bitset is : 00010011
string conversion by replacing 0 with T and 1 with P is : TTTPTTPP

bitset 上還有許多其他操作。還有一些可以使用的位運算子。這裡討論了 bitset 的基本函式和屬性。

更新於: 2019年10月4日

231 次檢視

開啟您的 職業生涯

透過完成課程獲得認證

開始學習
廣告

© . All rights reserved.