I have a function that returns a vector of bitset
s 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 bitset
s' 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?
(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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With