C++ bitset类
生活随笔
收集整理的這篇文章主要介紹了
C++ bitset类
小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.
bitset 模板類由若干個位(bit)組成,它提供一些成員函數(shù),使程序員不必通過位運算就能很方便地訪問、修改其中的任意一位。bitset 模板類在頭文件 中定義如下:
template <size_t N> class bitset {... };size_t 可看作 unsigned int。將 bitset 實例化時,N 必須是一個整型常數(shù)。例如:
bitset <40> bst;則 bst 是一個由 40 個位組成的對象,用 bitset 的成員函數(shù)可以方便地訪問其中任意一位。bitset 中的位從 0 開始編號,第 0 位是最右邊的位。
bitset 有許多成員函數(shù),有些成員函數(shù)執(zhí)行的就是類似于位運算的操作。bitset 成員函數(shù)列表如下:
bitset <N> & operator &= (const bitset <N> & rhs); //和另一個 bitset 對象進行與操作bitset <N> & operator |= (const bitset <N> & rhs); //和另一個 bitset 對象進行或操作bitset <N> & operator ^= (const bitset <N> & rhs); //和另一個 bitset 對象進行異或操作bitset <N> & operator <<= (size_t num); //左移 num 位bitset <N> & operator >>= (size_t num); //右移 num 位bitset <N> & set(); //將所有位全部設成 1bitset <N> & set(size_t pos, bool val = true); //將第 pos 位設為 valbitset <N> & reset(); //將所有位全部設成0bitset <N> & reset (size_t pos); //將第 pos 位設成 0bitset <N> & flip(); //將所有位翻轉(zhuǎn)(0變成1,1變成0)bitset <N> & flip(size_t pos); //翻轉(zhuǎn)第 pos 位reference operator[] (size_t pos); //返回對第 pos 位的引用bool operator[] (size_t pos) const; //返回第 pos 位的值reference at(size_t pos); //返回對第 pos 位的引用bool at (size_t pos) const; //返回第 pos 位的值unsigned long to_ulong() const; //將對象中的0、1串轉(zhuǎn)換成整數(shù)string to_string () const; //將對象中的0、1串轉(zhuǎn)換成字符串size_t count() const; //計算 1 的個數(shù)size_t size () const; //返回總位數(shù)bool operator == (const bitset <N> & rhs) const;bool operator != (const bitset <N> & rhs) const;bool test(size_t pos) const; //測試第 pos 位是否為 1bool any() const; //判斷是否有某位為1bool none() const; //判斷是否全部為0bitset <N> operator << (size_t pos) const; //返回左移 pos 位后的結(jié)果bitset <N> operator >> (size_t pos) const; //返回右移 pos 位后的結(jié)果bitset <N> operator ~ (); //返回取反后的結(jié)果bitset <N> operator & (const bitset <N> & rhs) const; //返回和另一個 bitset 對象 rhs 進行與運算的結(jié)果bitset <N> operator | (const bitset <N> & rhs) const; //返回和另一個 bitset 對象 rhs 進行或運算的結(jié)果bitset <N> operator ^ (const bitset <N> & rhs) const; //返回和另一個 bitset 對象 rhs 進行異或運算的結(jié)果bitset 的用法。
#include <iostream> #include <bitset> #include <string> using namespace std; int main() {bitset<7> bst1;bitset<7> bst2;cout << "1) " << bst1 << endl; //輸出 1) 0000000bst1.set(0,1);//將第0位變成1,bst1變?yōu)?0000001cout << "2) " << bst1 << endl; //輸出 2) 0000001bst1 <<= 4; //左移4位,變?yōu)?0010000cout << "3) " << bst1 << endl; //輸出 3) 0010000bst2.set(2);//第二位設置為1,bst2變成 0000100bst2 |=bst1; // bst2變成 0010100cout << "4) " << bst2 << endl; //輸出 4) 0010100cout << "5) " << bst2.to_ulong () << endl; //輸出 5) 20bst2.flip(); //每一位都取反,bst2變成 1101011bst1.set(3); //bst1變成 0011000bst2.flip(6); //bst2變成 0101011bitset<7> bst3 = bst2^ bst1;//bst3 變成 0110011cout << "6) " << bst3 << endl; //輸出 6) 0110011cout << "7) " << bst3[3] << "," << bst3[4] << endl; //輸出 7) 0,1return 0; }總結(jié)
以上是生活随笔為你收集整理的C++ bitset类的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: C++文件类
- 下一篇: Dev C++详细安装教程