stlport学习之bitset篇

学习bitset了,虽然网上已经有很多文章了,我也没有什么创新的,只是把所有能用的都放在这里了。

/********************************************************************
*
* 文件名称:test_bitset.cpp
* 摘 要:对stlport的bitset的一个全面的实验
*
* 当前版本:v0.1
* 作 者:福柯
* 完成日期:2007年01月02日
*
* Copyright (c) 2007,Programming Lab.
* All rights reserved.
*********************************************************************/

#include <iostream>
#include <bitset>
#include <string>

using namespace std;

int main(int argc, char *argv[])
{
      bitset<10> bit;  //测试变量,为了简单,设为10位

      //置位篇
       bit.set(2);   //在第2位置1,即:0000000100
      cout<<bit<<endl;

      bit.reset(3);  //在第3位置0,即:0000000000
      cout<<bit<<endl;

      bit.flip(3);  //第3位取反,即:0000001000
      cout<<bit<<endl;
     
      //计量篇
      cout<<bit.count()<<endl; //返回1的个数
      cout<<bit.size()<<endl;  //返回bit的位数

      //运算篇
       bit&=2;     //各种对位适用的操作 & | ^ ~  这里就不写了
       bit|=15;
       cout<<bit<<endl;

       //测试篇
        cout<<bit[2]<<endl;  //取第2位的值,和test一样
       cout<<(bit!=0?"true":"false")<<endl; //!=运算符
       cout<<(bit==1?"true":"false")<<endl;   //==运算符

      if (bit.any())  //如果任何一位为1,则bit.any()为true
     {
            cout<<"bit.any"<<endl;
     }

     if (bit.none())  //与any相对,在所有的位都是0的时候,bit.none返回true
     { 
           cout<<"bit.none"<<endl;
      }
 
     if (bit.test(3)) //测试某一位是否被置位
     {
            cout<<"bit[3] is set"<<endl;
      }

      //转换篇
      unsigned long  u = bit.to_ulong();  //按位转换到long
      string    str  =  bit.to_string<char,char_traits<char>,allocator<char>>();   //转换成一个string

     return 0;

最后是关于to_string的一点说明。是不是觉得这个写法很恶心?我也觉得很不爽,研究了一下原代码(其实就看了两眼)找出一个新法,不过,可能会有副作用,所以要慎用!

在#include<bitset>之前加一句
#define _STLP_NO_EXPLICIT_FUNCTION_TMPL_ARGS
就可以搞定了,直接str=bit.to_string();就行,不过,因为这个参数是为vc6以前的编译器兼容才设计的,所以会对其它的库产生影响,所以要小心使用。

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 5
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 5
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值