XOR BITSET将2D焦点存储为1D

XOR bitset when 2D bitset is stored as 1D

本文关键字:存储 1D 焦点 2D BITSET XOR      更新时间:2023-10-16

在您只关心速度时回答如何存储二进制数据?我想编写一些进行比较,所以我想使用std::bitset。但是,为了进行公平的比较,我希望1D std::bitset模仿2D。

所以没有:

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

我想使用:

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

优化数据局部性。但是,现在我应该如何存储和计算二进制代码之间的锤子距离?

#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]访问一个位。在您的2D位数组的概念模型中,它访问了ROW i和列0的位。

因此,v[i * D]boolqstd::bitset<D>,而将其应用于这些的位逻辑XOR运算符(^)是没有意义的。

如果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;
}