bitset用法详解

来源:互联网 发布:网址正则表达式 js 编辑:程序博客网 时间:2024/05/24 05:36

bitset<> bit(s),s可以是一个string对象,但是不能为char*或const char*,否则编译错误。如果string不是01串,怎会出现运行时错误。



如果bitset对象包含的二进制位数超过unsigned long的常数,将会产生编译错误。

#include <iostream>
#include <bitset>
using namespace std;
int main(void)
{
    bitset<103439432> temp;
    return 0;
}

103439432并没有大于unsigned long的最大值,上述程序成功运行。如果运行出错,可能原因是编译器的栈空间太小,需要对编译器进行设置。下面方法摘自http://who-know.com/tag/codeblocks/

01. Code::Blocks 之 Increase Stack Size 的方法

Settings -> Compiler and debugger -> Linker Settings -> Other linker options -> 加上 -Wl,-stack,填需要的大小
// eg : -Wl,-stack,50000000

#include <iostream>
#include <bitset>
using namespace std;
int main(void)
{
    bitset<4294967299> temp(0);
    return 0;
}

上述程序编译错误:error: integer constant is too large for "long" type.

#include <iostream>
#include <bitset>
using namespace std;
int main(void)
{
    const size_t size=4294967290ul; //取决于size_t的定义
    cout<<(int)size;
    bitset<size> temp(0);
    return 0;
}

上述程序仍然会引起编译错误,原因是编译器把4294967290ul转化为long类型,则实际定义的是bitset<-6u>,因此windows环境中,MinGW要注意bitset的size在long的范围内,而不是unsigned long的范围,其他系统或编译器未知。


#include <iostream>
#include <bitset>
using namespace std;
int main(void)
{
    bitset<0> temp(0);
    return 0;
}

bitset的size不能为0,编译错误。为负数时,也会有编译错误。


cout<<bitset;bitset将会从高到低位输出。


bitset.size()得到的是size_t类型,定义在cstddef头文件中。


cin>>bitset输入时如果超过bitset长度,则截取先输入的,如果输入的非01串,会截取先输入的01串,其余位补0。


#include <iostream>
#include <bitset>
using namespace std;
int main(void)
{
    bitset<15> temp1=0x2;
    bitset<129> temp2;
    cout<<sizeof(temp1)<<endl<<temp1<<endl<<temp1.size()<<endl;
    cout<<sizeof(temp2)<<endl<<temp2<<endl<<temp2.size()<<endl;
    return 0;
}

sizeof(temp1)的值为4,sizeof(temp2)的值为20。

sizeof和bitset.size()不同,取32的最小倍数。


bitset<n> b(u);可以用unsigned long类型对bitset变量初始化,但是如果是负数,则会出现警告。


bitset初始化为0串。


调用bitset<>的成员函数时,使用到pos(bitset中位的位置)必须保证pos<size,否则运行时异常终止,且要注意pos从0开始。

来自  http://blog.csdn.net/zcsylj/article/details/7354541

0 0
原创粉丝点击