C++中的位集,关于连续添加
Bitset in C++, about continuously add
我想向比特集添加1个值,直到它溢出,我想知道如何做到这一点,比如:
位集<20> foo;(foo=000000000000000000000)我们如何实现这个功能,连续添加一个
00000000000000000000>00000000000000000001>000000000000000000000000>00010>000000000000000000000000011,直到溢出?
我正在考虑两种方式;
foo.to_ulong();
如何将无符号长再次转换回位集?C++文档表明这是可能的,但在库中,我只能看到位集(无符号长val),它正在创建一个新的位集
2。不知怎的,位操作都被卡住了,需要的帮助
您可以使用以下内容:http://ideone.com/C8O8Qe
template <std::size_t N>
bool increase(std::bitset<N>& bs)
{
for (std::size_t i = 0; i != bs.size(); ++i) {
if (bs.flip(i).test(i) == true) {
return true;
}
}
return false; // overflow
}
然后迭代所有值:
std::bitset<20> bs;
do {
std::cout << bs << std::endl;
} while (increase(bs));
以下代码应该会对您有所帮助:
bitset<20> b;
bool overflow = false;
while( ! overflow ){
cout << b << endl; // prints bits in reversed order
int ipos = b.size();
overflow = true;
while( overflow && --ipos >= 0 ){
overflow = b[ipos];
b[ipos] = ! b[ipos];
}
}
由@Jarod42测试,谢谢。
相关文章:
- 将成员变量添加到共享库中的类中,不会破坏二进制兼容性吗
- 如何在C++中从两个单独的for循环中添加两个数组
- POCO::PostgreSQL:如何将std::vector支持添加到`Binder::bind`
- 如何仅为一个函数添加延迟
- 模板元程序查找相似的连续类型名称
- 如何防止 c++ 在从浮点型转换为双精度型(不适用于 IO)时添加额外的小数?
- 使用std::transform将一个范围的元素添加到另一个范围中
- 如何将更多文件夹添加到c++include路径
- 如何将元素添加到数组的线程安全函数?
- QT通过C++添加映射QML项目
- 如何将点击的信号和插槽添加到qt中的自定义按钮中
- 如何使用重载的相等(==)运算符向测试用例添加描述
- 为什么Mat类的两个对象可以在不重载运算符+的情况下添加
- 如何防止clang格式在流运算符调用之间添加换行符<<
- 通过在带有 C++ 的列表中添加连续元素来计算新的整数列表
- 在C 中添加连续的向量元素组的最快方法
- 如何将连续的内存块(动态地)添加到先前分配的动态内存中
- 在列中添加连续条目
- C++中的位集,关于连续添加
- 从输入中添加连续整数(从 Python 转换为 C++)