将 1 添加到 C++ 位集
add 1 to c++ bitset
我有一个给定长度的 c++ 位集。我想生成这个位集的所有可能组合,我想为此添加 1 2^bitset.length 时间。怎么做?增强库解决方案也是可以接受的
试试这个:
/*
* This function adds 1 to the bitset.
*
* Since the bitset does not natively support addition we do it manually.
* If XOR a bit with 1 leaves it as one then we did not overflow so we can break out
* otherwise the bit is zero meaning it was previously one which means we have a bit
* overflow which must be added 1 to the next bit etc.
*/
void increment(boost::dynamic_bitset<>& bitset)
{
for(int loop = 0;loop < bitset.count(); ++loop)
{
if ((bitset[loop] ^= 0x1) == 0x1)
{ break;
}
}
}
所有可能的组合?只需使用 64 位无符号整数,让您的生活更轻松。
不是最好的,而是蛮力方式,但您可以通过使用 to_ulong()
进行转换来添加 1
bitset<32> b (13);
b = b.to_ulong() + 1;
使用提升库,您可以尝试以下操作:
例如,长度为 4 的位集
boost::dynamic_bitset<> bitset;
for (int i = 0; i < pow(2.0, 4); i++) {
bitset = boost::dynamic_bitset<>(4, i);
std::cout << bitset << std::endl;
}
相关文章:
- 在 C++ 中将整数数组转换为位集表示形式的最佳方法?
- 位集元素迭代的抽象
- 如何为位集找到/实现一个好的哈希函数
- 将位集<64>转换为quint8
- 从 long 转换C++位集构造函数的复杂性是多少?
- 如何为具有整数名称的变量设置位集
- 将 1 添加到 32 位的位集
- 位集上的按位或给出错误的答案
- 位集构造函数中的一元按位或折叠
- C++11 模板函数"implicity"将位集<N>转换为"unsigned long"
- 从位集屏蔽特定模式
- 写入位集的速度不够快
- 如何将标准::位集<N>转换为标准::位集<M>?
- 将位集<64>转换为每 8 位字符串
- 将位集转换为有符号
- 位集<10>和位集<2>(输入[i])的差异,需要解释
- 如何将任何大小的位集传递给函数?
- 将位集写入文件时出错
- 使用位集获取数组项的条件总和,而无需使用循环
- C++:关于插入位集