【问题标题】:XOR bitset when 2D bitset is stored as 1D将 2D 位集存储为 1D 时的 XOR 位集
【发布时间】:2017-04-08 20:03:56
【问题描述】:

为了回答How to store binary data when you only care about speed?,我正在尝试写一些来做比较,所以我想使用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

【问题讨论】:

    标签: data-structure c++ performance bit-manipulation hamming-distance std-bitset


    【解决方案1】:

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

    所以v[i * D]boolqstd::bitset&lt;D&gt;,应用于这些的按位逻辑异或运算符 (^) 没有意义。

    如果v 用于表示大小为D 的二进制向量序列,则应改用std::vector&lt;std::bitset&lt;D&gt;&gt;。此外,std::bitset&lt;N&gt;::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;
    }
    

    【讨论】:

    • 但现在是二维数据结构,而不是一维数据结构,对吧? ://
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-06-26
    • 1970-01-01
    • 1970-01-01
    • 2023-03-12
    • 2015-02-17
    • 2015-12-01
    相关资源
    最近更新 更多