简化了位集算法的尝试
Simplifying a bit set algorithm attempt
本文关键字:算法 更新时间:2023-10-16
试图简化涉及位数组操作的赋值的这段工作但冗长的代码。到目前为止,我对set函数的了解(将数组中索引处的位设置为1):
// set bit with given index to 1
void BitArray::Set (unsigned int index){
switch( index%8 )
{
case 7:
barray[index/8] = barray[index/8] | 1;
break;
case 6:
barray[index/8] = barray[index/8] | 2;
break;
case 5:
barray[index/8] = barray[index/8] | 4;
break;
case 4:
barray[index/8] = barray[index/8] | 8;
break;
case 3:
barray[index/8] = barray[index/8] | 16;
break;
case 2:
barray[index/8] = barray[index/8] | 32;
break;
case 1:
barray[index/8] = barray[index/8] | 64;
break;
case 0:
barray[index/8] = barray[index/8] | 128;
break;
default: cout << "Error. Index less than 0. Cannot set the bit.";
} // end of switch( index )*/
因此,我要处理一个char数组中的一个元素,在这个元素上,我要遍历保持该索引的8位。
以下是我简化switch语句的尝试:
int location = index / 8;
int position = index % 8;
mask = (1 << position);
barray[location] = barray[location] | Mask(index);
这不是我想要的方式(如果我传入2作为要更改的索引,则将索引5处的位设置为"1")
感谢任何输入
实际上,读取位的顺序不是C(或C++)读取位的次序。您似乎是从左到右读取位,而对于C,"1"是"00000001"。因此,您应该以这种方式修复您的语句(也使用"|="运算符):
barray[location] |= 1 << (7 - position);
(我忽略了你的函数Mask(index)
,因为你没有向我们描述它)
看起来您需要的是定义int position = 7 - (index % 8);
。
相关文章:
- 为什么这个运算符<重载函数对 STL 算法不可见?
- 基于ELO的团队匹配算法
- C++选择排序算法中的逻辑错误
- 有没有办法将谓词中的元素偏移量传递给 std 算法?
- C++A*算法并不总是在路径中具有目标节点
- 排序算法c++
- 构建可组合有向图(扫描仪生成器的汤普森构造算法)
- 算法问题:查找从堆栈中弹出的所有序列
- 下面是排序算法O(n)吗
- KMP算法和LPS表构造的运行时间
- 为什么我的排序算法会更改数组值
- 求最大元素位置的分治算法
- 具有非整数边容量的最大流量的Dinic算法
- 到连接组件算法的问题(递归)
- STL算法函数在多个一维容器上的使用
- 读取最后一行代码算法 - c++ 时出现问题
- 括号更改 O(n) 算法
- std::unordered_map 搜索算法是如何实现的?
- 如何实现高效的算法来计算大型数据集的多个不同值?
- 如何在 Mac 上使用 c++17 并行标准库算法?