我在 Eigen 中有一个很长的 vector ,如下所示:
MatrixXi iIndex(1000000);
初始化为0,只有很短的连续部分(小于100)填充1
,位置是随机的。
我需要在一个长循环中做以下事情:
int count;
int position;
for(int i=0;i<99999;i++){
//... randomly fill iIndex will short `1` s
// e.g. index = (someVectorXi.array() == i).cast<int>();
count = iIndex.sum(); // count all the nonzero elements
//position the first nonzero element index:
for (int j=0; j<1000000;j++){
if(iIndex(j))
position = j;
}
}
但是真的很慢。
有什么办法可以加快速度吗?
最佳答案
我的 2 美分:将这些位分组,例如uint32_t,因此您可以检查 i32 是否与 0 不同。当它不同时,您可能需要更长的时间才能找出哪些位是 1。
假设位数是 32 的整数倍(使其更容易):
for (int i = 0; i < max / sizeof(uint32_t); ++i)
{
if (wordGrp[i] != 0)
{
uint32_t grp = wordGrp[i];
for (j = 0; j < BITS_PER_UINT32; j++)
{
if ((grp & 1) == 1) std::cout << "idx " << (i*32 + j) << " is 1\n";
grp >>= 1;
}
}
}
关于c++ - 如何有效地操作很长的 vector ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21141240/