从整数数组构造bitset [英] Construct bitset from array of integers

查看:130
本文介绍了从整数数组构造bitset的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

很容易从 uint64_t 构建 bitset <64>

uint64_t flags = ...;
std::bitset<64> bs{flags};

但是有一个很好的方法来构造 bitset< 64 * N& uint64_t [N] 中的,使 flags [0] 最低64位?

But is there a good way to construct a bitset<64 * N> from a uint64_t[N], such that flags[0] would refer to the lowest 64 bits?

uint64_t flags[3];
// ... some assignments
std::bitset<192> bs{flags};  // this very unhelpfully compiles
                             // yet is totally invalid

在循环中调用 set()

推荐答案

std :: bitset 没有范围构造函数,所以你必须循环,但使用 std :: bitset :: set()是underkill。 std :: bitset 支持二进制运算符,因此您至少可以批量设置64位:

std::bitset has no range constructor, so you will have to loop, but setting every bit individually with std::bitset::set() is underkill. std::bitset has support for binary operators, so you can at least set 64 bits in bulk:

  std::bitset<192> bs;

  for(int i = 2; i >= 0; --i) {
    bs <<= 64;
    bs |= flags[i];
  }

更新:在评论中,@icando比特转换对 std :: bitset 的O(N)操作的有效关注。对于非常大的比特组,这将最终吃掉大量处理的性能提升。在我的基准中,与单独设置比特并且不改变输入的简单循环相比, std :: bitset 的盈亏平衡点data:

Update: In the comments, @icando raises the valid concern that bitshifts are O(N) operations for std::bitsets. For very large bitsets, this will ultimately eat the performance boost of bulk processing. In my benchmarks, the break-even point for a std::bitset<N * 64> in comparison to a simple loop that sets the bits individually and does not mutate the input data:

int pos = 0;
for(auto f : flags) {
  for(int b = 0; b < 64; ++b) {
    bs.set(pos++, f >> b & 1);
  }
}

= 200 (使用libstdc ++和 -O2 在x86-64上为gcc 4.9)。 Clang执行有点差,甚至破坏 N == 160 。 Gcc与 -O3 将其推向 N == 250

is somewhere around N == 200 (gcc 4.9 on x86-64 with libstdc++ and -O2). Clang performs somewhat worse, breaking even around N == 160. Gcc with -O3 pushes it up to N == 250.

取较低端,这意味着如果要使用10000位或更大的位组,这种方法可能不适合您。在32位平台(如常见ARM ),阈值可能会降低,因此在这种平台上使用5000位位组时请记住。然而,我认为,在这之前的某个地方,你应该问自己,一个bitset是否真的是容器的正确选择。

Taking the lower end, this means that if you want to work with bitsets of 10000 bits or larger, this approach may not be for you. On 32-bit platforms (such as common ARMs), the threshold will probably lie lower, so keep that in mind when you work with 5000-bit bitsets on such platforms. I would argue, however, that somewhere far before this point, you should have asked yourself if a bitset is really the right choice of container.

这篇关于从整数数组构造bitset的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆