c++ - 如何有效地操作很长的 vector ?

标签 c++ loops vector indexing

我在 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/

相关文章:

arrays - Swift 按特定顺序加入 2 个数组

c - 使用 getNum();正确和无限循环问题

c++ - 一个 vector 在 2500 万个 vector 中的查找距离

c++ - malloc.c :2451: sYSMALLOc: Assertion . ..失败

c++ - 我可以做些什么来改进指针 vector 中的搜索?

c++ - 如何声明一个可以在整个程序中使用的全局变量

C++检查文件是否存在,如果存在,改变输出

c++ - cygwin 上的 g++ 与我在 Linux 平台上获得的有什么不同吗?

c - for 循环中的变量作用域

c++ - unique_ptrs 的循环 vector 并为运行时类型调用正确的重载