我想计算1
在同一位置的多个位集中的出现。每个位置的计数存储在一个向量中。
例如
b0 = 1011
b1 = 1110
b2 = 0110
----
c = 2231 (1+1+0,0+1+1,1+1+1,1+0+0)
我可以使用下面的代码轻松做到这一点,但这段代码似乎缺乏性能,但我不确定。所以我的问题很简单:有没有更快的方法来计算1
?
#include <bitset>
#include <vector>
#include <iostream>
#include <string>
int main(int argc, char ** argv)
{
std::vector<std::bitset<4>> bitsets;
bitsets.push_back(std::bitset<4>("1011"));
bitsets.push_back(std::bitset<4>("1110"));
bitsets.push_back(std::bitset<4>("0110"));
std::vector<unsigned> counts;
for (int i=0,j=4; i<j; ++i)
{
counts.push_back(0);
for (int p=0,q=bitsets.size(); p<q; ++p)
{
if (bitsets[p][(4-1)-i]) // reverse order
{
counts[i] += 1;
}
}
}
for (auto const & count: counts)
{
std::cout << count << " ";
}
}
for (int i=0,j=4; i<j; ++i)
{
for (int p=0,q=b.size(); p<q; ++p)
{
if(b[p][i])
{
c[p] += 1;
}
}
}