C++ Primer 學習筆記_14_標準模板庫_bitset位集合容器,_14_bitset

來源:互聯網
上載者:User

C++ Primer 學習筆記_14_標準模板庫_bitset位集合容器,_14_bitset

C++ Primer 學習筆記_14_標準模板庫_bitset位集合容器

bitset容器是一個bit位元素的序列容器,每個元素只佔一個bit位,取值為0或1,因而很節省記憶體空間。是一個bitset的儲存,它的10個元素只使用了兩個位元組的空間。

 
使用bitset需要聲明標頭檔”#include <bitset>”
 

1、建立bitset對象
建立bitset對象時,必須要指定容器的大小。bitset對象的大小一經定義,就不能修改了。下面這條語句就定義了bitset對象b,它能容納100個元素,即100個bit(位),此時,所有元素的值都為0。
bitset<100> b


2、設定元素值
(1)採用下標法
#include <bitset>#include <iostream>using namespace std;int main(){    bitset<10> b;    b[1] = 1;    b[6] = 1;    b[9] = 1;    for(int i = b.size() - 1; i >= 0; i--)        cout << b[i];    cout << endl;    return 0;}
運行結果:
1001000010

(2)採用set()方法,一次性將元素設定為1
#include <bitset>#include <iostream>using namespace std;int main(){    bitset<10> b;    b.set();    for(int i = b.size() - 1; i >= 0; i--)        cout << b[i];    cout << endl;    return 0;}
運行結果:
1111111111

(3)採用set(pos)方法,將某pos位設定為1
#include <bitset>#include <iostream>using namespace std;int main(){    bitset<10> b;    b.set(1, 1);    b.set(6, 0);    b.set(9, 1);    for(int i = b.size() - 1; i >= 0; i--)    {        cout << b[i];    }    cout << endl;    return 0;}
運行結果:
1000000010

(4)採用reset(pos)方法,將某pos位設定為0
#include <bitset>#include <iostream>using namespace std;int main(){    bitset<10> b;    b.set();    b.reset(0);    b.reset(5);    for(int i = b.size() - 1; i >= 0; i--)    {        cout << b[i];    }    cout << endl;    return 0;}
運行結果:
1111011110


3、輸出元素
(1)採用下標方法輸出元素
如上述代碼

(2)直接向輸出資料流輸出全部元素
#include <bitset>#include <iostream>using namespace std;int main(){    bitset<10> b;    b.set();    b.reset(0);    b.reset(5);    cout << b << endl;    return 0;}
運行結果:
1111011110

著作權聲明:本文為博主原創文章,未經博主允許不得轉載。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.