第1部分:在不使用指针和仅订阅的情况下引用数组第2部分:带指针的“......”

时间:2013-04-19 23:18:31

标签: c++ arrays pointers

#include <iostream>
#include <time.h>
using namespace std;

void my_func();
int main()
{
    float start_time = clock();
    cout << "Starting time of clock: " << start_time;
    cout << endl << endl;

    for (int i = 0; i < 100000; i++)
    {
        my_func();
    }

    float end_time = clock();
    cout << "Ending time of clock: " << end_time;
    cout << endl << endl;
}

void my_func()
{
    int my_array[5][5];
}

我需要编写一个程序,它只使用下标对二维数组的元素进行大量引用。这实际上是一个由两部分组成的项目,但我只关心让第一部分正确。第二部分允许使用指针但是现在,我只受“下标”(索引?)的约束。关于如何进行的任何建议?

由于Volkanİlbeyli,我已经成功完成了第一部分。我现在转到第二部分:

我需要编写一个程序,使用指针和指针算法对二维数组的元素进行大量引用。这是我到目前为止所做的:

#include <iostream>
#include <time.h>
using namespace std;

void my_func();

int main()
{

    float start = clock();

    for (int i = 0; i < 100000; i ++)
    {   
        my_func();
    }

    float end = clock();
    cout << "Ending time of clock: " << (end - start) / ((double)CLOCKS_PER_SEC);
}

void my_func()
{
    int my_array[10][10];

    for (int i = 0; i < 10; i++)
    {
        for (int j = 0; j < 10; j++)
        {
            *(my_array+i+j);
        }
    }
}

我已经完成了第一部分,现在我正在开展下一部分工作。我只是想知道我是否错过了什么。代码工作正常,程序也是如此。指针不是我的强项,我花了很多时间在互联网上找到我的答案。现在就指针和“指针算术”要求技术立场。

1 个答案:

答案 0 :(得分:1)

好吧,即使我无法理解你正在尝试的任务的目的或意义,如果我没有弄错,你会被要求通过使用索引来达到2D数组的元素。

考虑到您的代码,在my_func()中,您可以 访问这些元素。您只声明将使用大小为5x5的2D数组。要访问元素,(我认为)在你的情况下引用数组,你应该使用for循环和索引来访问数组的元素。

在你的情况下我应该这样:

void my_func()
{                                   //assuming that the usage of
    int my_array[1500][500] = {0};  //square matrice is not mandatory

    for(int i=0; i<1500 ; i++){
        for(int j=0; j<500 ; j++){
            my_array[i][j]; //no operation is done, only accessing the element
        }
    }

    return;
}

您还可以交换for循环以垂直方式访问数组,即通过第一列,然后是第二列,然后是第三列......这将使您的通过索引引用二维数组慢点。请参阅this post on SO为什么它会减慢以交换for循环,即将行列顺序更改为列行。

您还应注意如果您关注特定事件的关键时间测量,则应在启动时钟和结束时钟时仅包括该事件。在您的代码中,您还可以包括调用coutendl的时间以及与{em>数组引用无关的my_func()的调用时间。此外,我宁愿测量main()函数中的时间,因为访问2D数组不需要太多代码。如果它确实需要太多时间,我会调用函数,在里面声明时序变量,绝对不打印开始时间,在repeat-the-operations循环之前开始时间并在循环终止后停止。您可以看到this post以了解时间的测量和打印方式(当您需要考虑秒或毫秒等时)。