Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Returning a vector of bitsets in C++ [closed]

I have a function that returns a vector of bitsets containing ASCII values of its input.

typedef bitset<64> block;

vector<block> input_to_binary(string s)
{
    vector<block> v;
    block blk;
    int j = blk.size() - 1;


    for (int i = 0; i < s.size(); i++)
    {
        bitset<8> b(s[i]);

        for (int k = b.size() - 1; k >= 0; k--)
        {
            blk[j] = b[k];
            j--;
        }


        if (i % 8 == 7 || i == s.size() - 1)
        {
            // either the block is full now or this is the last character of the input
            v.push_back(blk);
            j = blk.size() - 1;

It's all fine inside the function:

            cout << "Just after the push:" << endl;
            for (int i = 0; i < v.size(); i++)
            {
                block blk = v[i];
                for (int i = blk.size() - 1; i >= 0; i--)
                    cout << blk[i] << "\t";
            }
        }

    }

    return v;
}

    Just after the push:
    0   1   0   0   1   0   0   0   0   1   1   0   0   1   0   1   0   1   1
    0   1   1   0   0   0   1   1   0   1   1   0   0   0   1   1   0   1   1
    1   1   0   0   1   0   1   1   0   0   0   0   1   0   0   0   0   0   0   
    1   0   0   1   0   0   0

After returning to main() though, the bitsets' data are lost:

int main()
{
    string s = "Hello, Hi, Goodbye";
    vector<block> v = input_to_binary(s);
    cout << "v.size() is " << v.size() << endl;
    for (int i = 0; i < v.size(); i++)
    {
        // block current = v[i];    //  tried either one
        block current(v[i]);
        cout << "block no. " << i << " with size " << current.size() << endl;
        for (int j = current.size() - 1; j >= 0; j--)
            cout << current[i] << "\t";
        cout << endl;
    }

}

    v.size() is 3
    block no. 0 with size 64
    0   0   0   0   0   0   0   0   0   0   0   0   0   0   0   0   0   0   0  
    0   0   0   0   0   0   0   0   0   0   0   0   0   0   0   0   0   0   0
    0   0   0   0   0   0   0   0   0   0   0   0   0   0   0   0   0   0   0
    0   0   0   0   0   0   0

Why is this happening? Is it about bitset's copy constructor, which I assume should work fine?

like image 404
Goh-shans Avatar asked Feb 07 '23 03:02

Goh-shans


1 Answers

(you may want to put on some forehead protection before reading further)

        cout << current[i] << "\t";

did you mean j? You're printing out the first element 64 times -- and based on your output from within the function, that value is 0.

Sometimes you stare at the code for so long, you start actually seeing your assumptions instead of what's on the screen :) Go take a break! You deserve it.

Looks like the STL writers are safe... at least for now :-D

like image 190
xaxxon Avatar answered Feb 19 '23 08:02

xaxxon