且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

在C ++中循环访问2d数组时提高O(n)

更新时间:2023-02-26 16:33:07

确保事情在内存中是连续的,因为缓存行为很可能会影响任何仅执行简单操作的代码的运行时。

Make sure things are contiguous in memory as cache behavior is likely to dominate the run-time of any code which performs only simple operations.

例如,don请勿使用:

For instance, don't use this:

int* a[10];
for(int i=0;i<10;i++)
  a[i] = new int[10];
//Also not this
std::vector< std::vector<int> > a(std::vector<int>(10),10);

使用此:

int a[100];
//or
std::vector<int> a(100);

现在,如果您需要2D访问,则使用:

Now, if you need 2D access use:

for(int y=0;y<HEIGHT;y++)
for(int x=0;x<WIDTH;x++)
  a[y*WIDTH+x];

使用1D访问进行紧密循环,不依赖邻居知识的全数组操作,或需要存储索引的情况:

Use 1D accesses for tight loops, whole-array operations which don't rely on knowledge of neighbours, or for situations where you need to store indices:

for(int i=0;i<HEIGHT*WIDTH;i++)
  a[i];

请注意,在以上两个循环中,触摸的项目数为 HEIGHT *两种情况下的宽度都为WIDTH 。尽管可能会出现,但其中一个的时间复杂度为 O(N ^ 2),而另一个 O(n) ,很明显,在两种情况下,完成的工作净额都是 HEIGHT * WIDTH 。***将 N 视为操作涉及的项目总数,而不是涉及其接触方式的属性。

Note that in the above two loops the number of items touched is HEIGHT*WIDTH in both cases. Though it may appear that one has a time complexity of O(N^2) and the other O(n), it should be obvious that the net amount of work done is HEIGHT*WIDTH in both cases. It is better to think of N as the total number of items touched by an operation, rather than a property of the way in which they are touched.