在C++STL中提供了位图的库bitset类,下面记录一下bitset的使用
template <size_t N> class bitset; //N: Number of bits to contain构造函数
(1)bitset ( );//空的,默认设置为0 (2)bitset ( unsigned long val ); (3)参数可以使字符串,使用:
// constructing bitsets #include <iostream> #include <string> #include <bitset> using namespace std; int main () { bitset<10> first; // empty bitset bitset<10> second (120ul); // initialize from unsigned long bitset<10> third (string("01011")); // initialize from string cout << first << endl; // 00000 00000 cout << second << endl; // 00011 11000(120的二进制表示) cout << third << endl; // 00000 01011 return 0; }Bit access:operator[]
bool operator[] ( size_t pos ) const; reference operator[] ( size_t pos );使用
bitset<4> mybits; mybits[1]=1; // 0010 mybits[2]=mybits[1]; // 0110 cout << "mybits: " << mybits << endlBit operations:
bit::set
bitset<N>& set ( ); //全部设置为1 bitset<N>& set ( size_t pos, bool val = true );bit::reset
bitset<N>& reset ( ); //全部设置为0,复位 bitset<N>& reset ( size_t pos ); //指定位置设为0bitset::flip 取反
changes all 0s for 1s and all 1s for 0s. 改变所有的0位1,改变所有的1位0。
bitset<N>& flip ( ); //全部取反 bitset<N>& flip ( size_t pos );//指定位置取反Bitset operations:
(1) bitset::to_ulong 将位图转换为unsigned long
unsigned long to_ulong ( ) const; //Convert to unsigned long integer bitset<4> mybits; // mybits: 0000 mybits.set(); // mybits: 1111 mybits.to_ulong(); // 15(2)bitset::to_string
template <class charT, class traits, class Allocator> basic_string<charT,traits,Allocator> to_string() const; //Convert to string使用
string mystring; bitset<4> mybits; // mybits: 0000 mybits.set(); // mybits: 1111 mystring=mybits.to_string<char,char_traits<char>,allocator<char> >(); cout << "mystring: " << mystring << endl; //1111(3) bitset::count
统计位图中1的个数
size_t count ( ); //Count bits set使用
bitset<8> myset (string("10110011")); cout << "myset has " << int(myset.count()) << " ones "; cout << "and " << int(myset.size()-myset.count()) << " zeros.\n"; // myset has 5 ones and 3 zeros(4)bitset::size
size_t size() const; //Return size //Returns the number of bits in the bitset.(5)bitset::test
判断某个位置是否被设置为true, 注:位图是从右边起始位置为0的位置,
bool test ( size_t pos ) const; //Return bit value //Returns whether bit at position pos in the bitset is set使用
bitset<5> mybits (string("01011")); cout << "mybits contains:\n"; cout << boolalpha; for (size_t i=0; i<mybits.size(); ++i) cout << mybits.test(i) << endl;输出
mybits contains: true true false true false(5)bitset::any
测试所有的bit位是否被设置
bool any ( ) const; //Test if any bit is set //Returns whether any of the bits in the bitset is set.(6)bitset::none
测试是否所有bit位没有被设置
bool none ( ) const; //Test if no bit is set //Returns whether none of the bits in the bitset are set.位图的实现可以参考上篇博客 http://blog.csdn.net/wenqiang1208/article/details/76724338