Bitcounting可以通过多种方式完成,例如.with set bit iterator,unset bit iterator,pre-computed bits with lookup tables或parallel counting.正如我通过搜索网络所发现的那样,当未设置的位数较少时,未设置的位迭代器很快,而相反的位置则设置位迭代器.但是什么时候应该使用并行计数,特别是MIT HAKMEM(见下文)?它似乎相当快,虽然可能比查找表慢.在速度方面,它与set/unset位相比总是更好吗?还有其他一些关于速度和记忆的选择吗?
int BitCount(unsigned int u) {
unsigned int uCount;
uCount = u - ((u >> 1) & 033333333333) - ((u >> 2) & 011111111111);
return ((uCount + (uCount >> 3)) & 030707070707) % 63;
}
Run Code Online (Sandbox Code Playgroud) 我正在vector<bool>
实施.我保存一个unsigned int并使用按位运算来得到一个true和false的向量.我的问题是这个; 我可以通过operator []访问各个位,但是如何获得对这样的位的引用以便我可以写入
Vector<bool> v(5, true);
v[3] = false;
Run Code Online (Sandbox Code Playgroud)
在某处我听说你不应该对各个位做引用/指针.代码摘要,适用于检索位值:
...
unsigned int arr; // Store bits as unsigned int
unsigned int size_vec; // The size of "bool vector"
...
bool& Vector<bool>::operator[](unsigned int i) {
if (i>=vec_size || i<0) {
throw out_of_range("Vector<bool>::operator[]");
}
int index = 1 << (i-1);
bool n = false;
if (index & arr) {
n=true;
}
return n;
};
Run Code Online (Sandbox Code Playgroud)
那么,如何才能返回某种参考,从而可以改变各个位?