std::bitset



bitset

複数のbool型を連ねたようなもの.たくさんのフラグを格納するのに便利. また,bool型は2値しかとらないのに1バイト領域を必要とし,メモリの無駄となる. bitsetを使うことでメモリの節約にもなる.

#include <bitset>

使用例

  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
#include <cstdio>
#include <string>
#include <bitset>
using namespace std;
 
enum Draw
{
    ID_DISPLAY_FLUID = 0, 
    ID_DISPLAY_RIGID, 
    ID_DISPLAY_CELLS, 
    ID_DISPLAY_BC, 
    ID_DISPLAY_NORMAL, 
    ID_DISPLAY_VELOCITY, 
};
 
std::bitset<8> g_bsDraw;    std::bitset<8> g_bsDraw2((string)"00101001");    std::bitset<8> g_bsDraw3((unsigned long)0xFF);     
int main(void)
{
    g_bsDraw.reset();        
        g_bsDraw.set(ID_DISPLAY_FLUID, 1);
    g_bsDraw.set(ID_DISPLAY_BC, 1);
    g_bsDraw.set(ID_DISPLAY_VELOCITY, 1);
    
        g_bsDraw.flip(ID_DISPLAY_NORMAL);
    
        g_bsDraw.flip();
 
        if(g_bsDraw.at(ID_DISPLAY_NORMAL)){
        printf("normal on\n");
    }
    else{
        printf("normal off\n");
    }
    
        if(g_bsDraw[ID_DISPLAY_NORMAL]){
        printf("normal on\n");
    }
    else{
        printf("normal off\n");
    }
 
        printf("bitset : %s\n", g_bsDraw.to_string().c_str());
 
        printf("bitset : %d\n", g_bsDraw.to_ulong());
 
        printf("true : %d / %d\n", g_bsDraw.count(), g_bsDraw.size());
 
        g_bsDraw.set();
 
        g_bsDraw.reset();
 
        if(!g_bsDraw.any()) printf("all false\n");
 
        if(g_bsDraw.none()) printf("all false\n");
 
    return 0;
}

オペレータ

  • ==,!= : bitset同士の比較
  • &=,^=,|=,~ : 論理和,排他的論理和,論理積,否定
  • <<,>>,<<=,>>= : シフト演算

トップ   編集 凍結 差分 履歴 添付 複製 名前変更 リロード   新規 一覧 検索 最終更新   ヘルプ   最終更新のRSS
Last-modified: 2022-11-30 (水) 13:48:10