当 2D bitset 存储为 1D 时 XOR bitset

XOR bitset when 2D bitset is stored as 1D

为了回答,我想写一些做比较,所以我想用std::bitset。但是,为了公平比较,我想要一个 1D std::bitset 来模拟 2D。

所以不用:

bitset<3> b1(string("010"));
bitset<3> b2(string("111"));

我想使用:

bitset<2 * 3> b1(string("010111"));

优化数据局部性。但是,现在我遇到了 How should I store and compute Hamming distance between binary codes? 的问题,如我的最小示例所示:

#include <vector>
#include <iostream>
#include <random>
#include <cmath>
#include <numeric>
#include <bitset>

int main()
{
    const int N = 1000000;
    const int D = 100;
    unsigned int hamming_dist[N] = {0};
    std::bitset<D> q;
    for(int i = 0; i < D; ++i)
        q[i] = 1;

    std::bitset<N * D> v;
    for(int i = 0; i < N; ++i)
        for(int j = 0; j < D; ++j)
            v[j + i * D] = 1;


    for(int i = 0; i < N; ++i)
        hamming_dist[i] += (v[i * D] ^ q).count();

    std::cout << "hamming_distance = " << hamming_dist[0] << "\n";

    return 0;
}

错误:

Georgioss-MacBook-Pro:bit gsamaras$ g++ -Wall bitset.cpp -o bitset
bitset.cpp:24:32: error: invalid operands to binary expression ('reference' (aka
      '__bit_reference<std::__1::__bitset<1562500, 100000000> >') and
      'std::bitset<D>')
                hamming_dist[i] += (v[i * D] ^ q).count();
                                    ~~~~~~~~ ^ ~
/Library/Developer/CommandLineTools/usr/bin/../include/c++/v1/bitset:1096:1: note: 
      candidate template ignored: could not match 'bitset' against
      '__bit_reference'
operator^(const bitset<_Size>& __x, const bitset<_Size>& __y) _NOEXCEPT
^
1 error generated.

这是因为它不知道什么时候停止!我如何告诉它在处理 D 位后停止?


我的意思是不使用 2D

问题是 v[i * D] 访问了一个位。在您的二维位数组的概念模型中,它访问 i 行和 0 列的位。

所以 v[i * D] 是一个 boolq 是一个 std::bitset<D>,并且应用于这些的按位逻辑异或运算符 (^) 不没道理。

如果 v 表示大小为 D 的二元向量序列,您应该改用 std::vector<std::bitset<D>>。此外,std::bitset<N>::set() 将所有位设置为 1

#include <vector>
#include <iostream>
#include <random>
#include <cmath>
#include <numeric>
#include <bitset>

int main()
{
    const int N = 1000000;
    const int D = 100;

    std::vector<std::size_t> hamming_dist(N);

    std::bitset<D> q;
    q.set();

    std::vector<std::bitset<D>> v(N);
    for (int i = 0; i < N; ++i)
    {
        v[i].set();
    }

    for (int i = 0; i < N; ++i)
    {
        hamming_dist[i] = (v[i] ^ q).count();
    }

    std::cout << "hamming_distance = " << hamming_dist[0] << "\n";

    return 0;
}