Search code examples
c++vectorstdbitset

Generating binary number using bitset causing segmentation fault in c++


Generating binary representation of numbers from 0 to 255. This is causing segmentation fault. Kindly enlighten.

    vector<bitset<7>> vb;
    for (i = 0; i < 256; i++)
    {
        bitset<7> b(i);
        vb[i] = b;
    }

    //print 
    for(i=0;i<256;i++){
        cout<<vb[i]<<"\n";

Solution

  • Your vector is of size 0. Either use

    vb.push_back(b);
    

    or initialize a size like:

    vector<bitset<7>> vb(256);