在 C++ 中返回位集向量

Returning a vector of bitsets in C++

我有一个函数 returns 包含其输入的 ASCII 值的 bitset 向量。

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;

函数里面没问题:

            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

虽然返回 main() 后,bitset 的数据丢失了:

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

为什么会这样?是关于 bitset 的复制构造函数,我认为它应该可以正常工作吗?

(您可能需要在进一步阅读之前戴上一些前额保护装置)

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

你是说j吗?您打印出第一个元素 64 次——根据函数内的输出,该值为 0。

有时您盯着代码看太久,您开始真正看到您的假设,而不是屏幕上显示的内容:) 休息一下吧!你值得拥有

看起来 STL 编写器是安全的...至少现在是这样:-D